package com.mission.schedule.fragment;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.CommonDialog.CalenderAddCContentDialog;
import com.mission.schedule.CommonDialog.CalenderAddDContentDialog;
import com.mission.schedule.CommonDialog.CalenderColorDialog;
import com.mission.schedule.CommonDialog.CalenderFlagDialog;
import com.mission.schedule.CommonDialog.CalenderTopCenterDialog;
import com.mission.schedule.CommonDialog.LoginDownServiceDialog;
import com.mission.schedule.CommonDialog.MonthFragmentAddDialog;
import com.mission.schedule.CommonDialog.ReminderDialog;
import com.mission.schedule.CommonDialog.RiLiDialog;
import com.mission.schedule.CommonDialog.SixNewTaskDialog;
import com.mission.schedule.CommonDialog.YuyinDetailDialog;
import com.mission.schedule.R;
import com.mission.schedule.activity.CalenderNoteEditActivity;
import com.mission.schedule.activity.ComeFriendSchActivity;
import com.mission.schedule.activity.DateCalendarActivity;
import com.mission.schedule.activity.EditSchActivity;
import com.mission.schedule.activity.GuoQiWeiJieShuActivity;
import com.mission.schedule.activity.HelpActivity;
import com.mission.schedule.activity.ImportantSchActivity;
import com.mission.schedule.activity.MainActivity;
import com.mission.schedule.activity.MonthViewActivity;
import com.mission.schedule.activity.NewMyActivity;
import com.mission.schedule.activity.NewMyAppSetActivity;
import com.mission.schedule.activity.NewSixTaskDetailActivity;
import com.mission.schedule.activity.NoteEditActivity;
import com.mission.schedule.activity.PhoneCodeLoginActivity;
import com.mission.schedule.activity.QDFXDetailActivity;
import com.mission.schedule.activity.RecommendActivity;
import com.mission.schedule.activity.RepeatDaoQiDateActivity;
import com.mission.schedule.activity.SelectionFirendActivity;
import com.mission.schedule.activity.TagSerachActivity;
import com.mission.schedule.activity.WebViewActivity;
import com.mission.schedule.activity.YiQianActivity;
import com.mission.schedule.add603.NewInformationActivity;
import com.mission.schedule.add603.bean.UpNew;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.BackgroundBean;
import com.mission.schedule.bean.CalenderNoteBean;
import com.mission.schedule.bean.MySchBean;
import com.mission.schedule.bean.RepeatBean;
import com.mission.schedule.bean.WBA_FindFunctionMy;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.calendar.CaledarAdapter;
import com.mission.schedule.calendar.CalendarBean;
import com.mission.schedule.calendar.CalendarDateView;
import com.mission.schedule.calendar.CalendarUtil;
import com.mission.schedule.calendar.CalendarView;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.constants.Const;
import com.mission.schedule.constants.FristFragment;
import com.mission.schedule.constants.PostSendMainActivity;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.db.DBSourse;
import com.mission.schedule.entity.CLRepeatTable;
import com.mission.schedule.entity.LocateAllNoticeTable;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.my160920.FrendLyActivity;
import com.mission.schedule.my160920.bean.LyNewNumBean;
import com.mission.schedule.my160920.widget.CircleImageView;
import com.mission.schedule.newAdapter.CalenderAdapter;
import com.mission.schedule.newAdapter.CustomLinearLayoutManager;
import com.mission.schedule.service.DownCalenderNoteService;
import com.mission.schedule.service.DownCalenderService;
import com.mission.schedule.service.DownImageService;
import com.mission.schedule.service.DownRepeatService;
import com.mission.schedule.service.LocalSynService;
import com.mission.schedule.service.UpdataTagService;
import com.mission.schedule.sinaadd.BaseDialog;
import com.mission.schedule.sinaadd.KickBackAnimator;
import com.mission.schedule.utils.AfterPermissionGranted;
import com.mission.schedule.utils.BetterHighlightSpan;
import com.mission.schedule.utils.CalendarChange;
import com.mission.schedule.utils.CalendarChangeValue;
import com.mission.schedule.utils.CharacterUtil;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.DialogBarView;
import com.mission.schedule.utils.DialogCallback;
import com.mission.schedule.utils.DialogWidget;
import com.mission.schedule.utils.DisplayUtils;
import com.mission.schedule.utils.EasyPermissions;
import com.mission.schedule.utils.InWeekUtils;
import com.mission.schedule.utils.JsonParser;
import com.mission.schedule.utils.MyLinearLayout;
import com.mission.schedule.utils.MyViewPager;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.ReadTextContentXml.ReadWeiXinXml;
import com.mission.schedule.utils.RepeatDateUtils;
import com.mission.schedule.utils.RepeatSetChildEndUtils;
import com.mission.schedule.utils.SchDateComparator;
import com.mission.schedule.utils.ScreenUtil;
import com.mission.schedule.utils.ScreenUtils;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;
import com.mission.schedule.utils.UriUtils;
import com.mission.schedule.utils.Utils;
import com.mission.schedule.view.CycleWheelView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.mission.schedule.calendar.CalendarFactory.getMonthOfDayList;

public class MyScheduleFragment extends BaseFragment implements OnClickListener, DialogCallback, EasyPermissions.PermissionCallbacks, CalendarView.OnItemClickListener {//
    /**
     * 进行日程操作时日程所在列表的位置
     */
    private int opeartPosition = -1;
    /**
     * 进行日程操作的类型 0 新增 1 删除 2 修改 3 无操作
     */
    private int opeartType = 3;
    /**
     * 进行日程操作时的日程ID
     */
    private String opeartSchID = "";

    private ArrayList<Map<String, String>> mList = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> unlist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> todaylist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> tomorrowlist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> inweeklist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> outweeklist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> comelist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> otherlist = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, String>> yestodaylist = new ArrayList<Map<String, String>>();
    private RecyclerView recyclerView;
    private CalenderAdapter adapter = null;
    private boolean isShow = false;// 判断是否已经显示
    public static LinearLayout top_ll_left, delete_ll;
    private TextView guoqiweijieshu_tv, nongli, all_tv, today_tv, top_left_ric, top_left_iv, top_right_iv, freshLayout_header;// 过期为结束个数
    ImageView iv_more_down;// 设置铃声是否静音
    private LinearLayout all_today;

    private RelativeLayout up_down, tixing_rl;
    private RelativeLayout top_ll_right;
    private ImageButton add_btn_image;
    private int pageIndex = 1;
    private int timeType = 9;// 8以前,9今后,10本周17已发出,5刷新隐藏
    int index = 0;
    private String postpone = "0";// 顺延
    View view;

    SharedPrefUtil sharedPrefUtil = null;
    // TextView tv_schedule_count;
    // TextView tv_my_count;
    String userid, updatetime;

    String myfriendscount;
    static Context context;
    String localpath;
    int width;
    int heigth;
    String untaskend;
    private CircleImageView image_img;

    int uncount = 0;// 今日待办个数
    int todaycount = 0;// 今日日程个数
    int tomorrowcount = 0;// 明天日程个数
    int inweekcount = 0;// 一周以内日程个数
    int outweekcount = 0;// 一周以外日程个数
    String outweekfag = "1";
    String firstlogin = "0";
    String time;
    String ringdesc;
    String ringcode;
    String delaytime = "";

    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    private SharedPreferences mSharedPreferences;

    String soundstate;
    String wakestate;
    private Vibrator vibrator;

    TextView count_tv, myschedule_title;
    App application = App.getDBcApplication();
    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    InWeekUtils inWeekUtils = new InWeekUtils();
    private DialogWidget dialog;
    boolean autoFag = false;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;
    RepeatSetChildEndUtils repeatSetChildEndUtils = new RepeatSetChildEndUtils();

    public static List<Map<String, String>> schIDList = new ArrayList<Map<String, String>>();
    String permissionState = "0";

    private ImageLoader imageLoader;
    private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
    private DisplayImageOptions options;
    ImageView news_img;
    SmartRefreshLayout refreshLayout;
    ClassicsHeader month_view_header;
    CalendarView calenderView;
    LinearLayout month_layout;
    RelativeLayout sch_layout;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_myschedule, container, false);
        return view;
    }

    /**
     * 图片加载第一次显示监听器
     *
     * @author Administrator
     */
    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    newtype ntype = null;
    appwidget appwidget = null;
    boolean isCreate = false;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && !isShow) {
            isShow = true;
            init();
//            if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
////                checkfindMess();
//                loadData(3, "");
//                DownFrendCalenderLy();
//            }
        }
    }

    private void getJson() {
        new Thread(() -> {
            StringBuilder sb = new StringBuilder();
            try {
                AssetManager assetManager = context.getAssets();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(assetManager.open("cytx.json")));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
                sharedPrefUtil.putString(context, ShareFile.USERFILE,
                        ShareFile.CYTXJSON, sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }


    View headView;
    ClassicsHeader classicsHeader;

    @SuppressLint("NewApi")
    private void init() {
        context = getActivity();
        EventBus.getDefault().register(this);
        receiver = new UpdateDataReceiver();
        imageLoader = ImageLoader.getInstance();
        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        sharedPrefUtil = new SharedPrefUtil(getActivity(), ShareFile.USERFILE);
        userid = sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.USERID, "");
        updatetime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UPDATESETTIME, "");

        IntentFilter filter = new IntentFilter();
        filter.addAction(Const.SHUAXINDATA);
        filter.addAction("dismiss");
        getActivity().registerReceiver(receiver, filter);

        localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("noticeOnRefresh");
        noticeOnRefresh = new NoticeOnRefresh();
        localBroadcastManager.registerReceiver(noticeOnRefresh, intentFilter);

        IntentFilter intentFilter2 = new IntentFilter();
        intentFilter2.addAction("noticeOnRefresh2");
        noticeOnRefresh2 = new NoticeOnRefresh2();
        localBroadcastManager.registerReceiver(noticeOnRefresh2, intentFilter2);

        myschedule_title = view.findViewById(R.id.myschedule_title);
        nongli = view.findViewById(R.id.nongli);
        nongli.setOnClickListener(this);
        myschedule_title.setText(Today() + " " + Week());
        listBeanList = new ArrayList<>();

        localpath = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
        myfriendscount = sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.COUNT, "0");

        headView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_myschedule_head, null);
        delete_ll = view.findViewById(R.id.delete_ll);
        count_tv = view.findViewById(R.id.count_tv);
        guoqiweijieshu_tv = view.findViewById(R.id.guoqiweijieshu_tv);
        up_down = view.findViewById(R.id.up_down);
        all_today = view.findViewById(R.id.all_today);
        all_tv = view.findViewById(R.id.all);
        top_left_ric = view.findViewById(R.id.top_left_ric);
        today_tv = view.findViewById(R.id.today);
        top_left_iv = view.findViewById(R.id.top_left_iv);
        top_right_iv = view.findViewById(R.id.top_right_iv);
        freshLayout_header = view.findViewById(R.id.freshLayout_header);

        all_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                all_today_i = 0;
                all_tv.setBackground(context.getResources().getDrawable(R.drawable.s_2));
                all_tv.setTextColor(context.getResources().getColor(R.color.title0));
                today_tv.setBackground(context.getResources().getDrawable(R.drawable.s_1));
                today_tv.setTextColor(context.getResources().getColor(R.color.wodericheng_biaoti1));
                loadData(3, "");
            }
        });
        today_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                all_today_i = 1;
                today_tv.setBackground(context.getResources().getDrawable(R.drawable.s_2));
                today_tv.setTextColor(context.getResources().getColor(R.color.title0));
                all_tv.setBackground(context.getResources().getDrawable(R.drawable.s_1));
                all_tv.setTextColor(context.getResources().getColor(R.color.wodericheng_biaoti1));
                loadData(3, "");
            }
        });

        up_down.setOnClickListener(this);
        tixing_rl = view.findViewById(R.id.tixing_rl);
        tixing_rl.setVisibility(View.GONE);
        tixing_rl.setOnClickListener(this);
        up_down.setVisibility(View.GONE);

        refreshLayout = view.findViewById(R.id.refreshLayout);
        month_layout = view.findViewById(R.id.month_layout);
        sch_layout = view.findViewById(R.id.sch_layout);
//        loadMonthView();
        classicsHeader = new ClassicsHeader(context);
        refreshLayout.setRefreshHeader(classicsHeader);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {


                if (NetUtil.getConnectState(context) == NetWorkState.NONE) {
                    refreshLayout.finishRefresh();
                } else {
                    onRefreshs();
                }
//                refreshLayout.finishRefresh();
//                month_layout.setVisibility(View.VISIBLE);
//
//                date_ll.setVisibility(View.GONE);
//                ll_back.setVisibility(View.VISIBLE);
//                top_ll_right_m.setVisibility(View.VISIBLE);
//                loaddata();
//                ValueAnimator fadeAnim = ObjectAnimator.ofFloat(month_layout, "translationY", -ScreenUtils.getScreenHeight(context), 0f);
//                fadeAnim.setDuration(200);
//                fadeAnim.start();
//                Intent intent = new Intent("noticeOnRefresh1");
//                intent.putExtra("isMonth", true);
//                localBroadcastManager.sendBroadcast(intent);
            }
        });

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        news_img = view.findViewById(R.id.news_img);

        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            refreshLayout.setEnableRefresh(true);
        } else {
            refreshLayout.setEnableRefresh(false);
        }

        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            options = new DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.b1)
                    .showImageForEmptyUri(R.mipmap.b1)
                    .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                    .cacheOnDisc(true).cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                    .build();
        } else {
            options = new DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.turh)
                    .showImageForEmptyUri(R.mipmap.turh)
                    .showImageOnFail(R.mipmap.turh).cacheInMemory(true)
                    .cacheOnDisc(true).cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                    .build();
        }

        image_img = view.findViewById(R.id.image_img);
//        image_img.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(context, NewMyAppSetActivity.class);
//                context.startActivity(intent);
//            }
//        });
//        String image_head = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "");
//        String imageUrl = URLConstants.图片 + image_head + "&imageType=2&imageSizeType=3";
//        String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
//        File outfile = new File(dicr, "TimeApp");
//        // 如果文件不存在，则创建一个新文件
//        if (!outfile.isDirectory()) {
//            try {
//                outfile.mkdir();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

//        Bitmap bitmapHead = BitmapFactory.decodeFile(outfile + "/" + image_head.replace('/', '0'));
//        if (bitmapHead == null) {
//            imageLoader.displayImage(imageUrl, image_img, options, animateFirstListener);
//            Intent intent = new Intent(context, DownImageService.class);
//            intent.setAction("downimage");
//            intent.putExtra("url", imageUrl);
//            intent.putExtra("name", image_head.replace('/', '0'));
//            context.startService(intent);
//        } else {
//            image_img.setImageBitmap(bitmapHead);
//        }

        top_ll_left = view.findViewById(R.id.top_ll_left);
        top_ll_left.setOnClickListener(this);

        top_ll_right = view.findViewById(R.id.top_ll_right);
        top_ll_right.setOnClickListener(this);
        add_btn_image = view.findViewById(R.id.add_btn_image);
        add_btn_image.setOnClickListener(this);
        add_btn_image.setOnLongClickListener(v -> {
            dialogOnClick();
            return false;
        });
        iv_more_down = view.findViewById(R.id.iv_more_down);
        iv_more_down.setOnClickListener(this);
        LinearLayout myschedule_ll = view.findViewById(R.id.myschedule_ll);

        myschedule_ll.setOnClickListener(this);

        ntype = new newtype();
        IntentFilter ifd = new IntentFilter();
        ifd.addAction("ntype");
        getActivity().registerReceiver(ntype, ifd);

        appwidget = new appwidget();
        IntentFilter ifds = new IntentFilter();
        ifds.addAction("appwidget");
        getActivity().registerReceiver(appwidget, ifds);


        /**
         * 获取屏幕的高度和宽度
         */
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;
        heigth = metric.heightPixels;

        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(getActivity(), mInitListener);

        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(getActivity(), mInitListener);
        mSharedPreferences = context.getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
        firstlogin = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if ("0".equals(firstlogin)) {
                if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                    if ("0".equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0"))) {
                        LoginDownServiceDialog loginDownServiceDialog = new LoginDownServiceDialog(
                                context, R.style.dialog_translucent, getActivity().getWindowManager());
                        loginDownServiceDialog.show();
                    }
                    if ("0".equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISSHOWPROGRESS, "0"))) {
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISSHOWPROGRESS, "1");
                    }
                }
            }
            showSM();
        } else {
            showSM();
        }
        isPrepared = true;
        permissionState = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0");
        if ("0".equals(permissionState)) {
            checkPhonePermission();
        }
        lazyLoad();
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APPWIDGETADDTYPE, "0");

        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CYTXJSON, "").equals("")) {
            getJson();
        }

        loadData(3, "");

//        if (sharedPrefUtil.getBoolean(ShareFile.MONTH_SHOW, false)) {
//            month_layout.setVisibility(View.VISIBLE);
//            date_ll.setVisibility(View.GONE);
//            ll_back.setVisibility(View.VISIBLE);
//            top_ll_right_m.setVisibility(View.VISIBLE);
//            loaddata();
//            Intent intent1 = new Intent("noticeOnRefresh1");
//            intent1.putExtra("isMonth", true);
//            localBroadcastManager.sendBroadcast(intent1);
//            sharedPrefUtil.putBoolean(ShareFile.MONTH_SHOW, false).commit();
//        }
//
//        onRefreshs();

    }


    public static boolean copy(String fromFile, String toFile) {
        //要复制的文件目录
        File[] currentFiles;
        File root = new File(fromFile);
        //如同判断SD卡是否存在或者文件是否存在
        //如果不存在则 return出去
        if (!root.exists()) {
            return false;
        }
        //如果存在则获取当前目录下的全部文件 填充数组
        currentFiles = root.listFiles();

        //目标目录
        File targetDir = new File(toFile);
        //创建目录
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        //遍历要复制该目录下的全部文件
        for (int i = 0; i < currentFiles.length; i++) {
            if (currentFiles[i].isDirectory())//如果当前项为子目录 进行递归
            {
                copy(currentFiles[i].getPath() + "/", toFile + currentFiles[i].getName() + "/");

            } else//如果当前项为文件则进行文件拷贝
            {
                CopySdcardFile(currentFiles[i].getPath(), toFile + "/" + currentFiles[i].getName() + "1");
            }
        }
        return true;
    }

    public static boolean CopySdcardFile(String fromFile, String toFile) {
        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return true;

        } catch (Exception ex) {
            return false;
        }
    }

    private void uploadJvBaoContent(String imagepath) {
        if (NetUtil.getConnectState(context) == NetUtil.NetWorkState.NONE) {
            Toast.makeText(context, "网络异常，请检查网络！", Toast.LENGTH_SHORT).show();
        } else {
            HttpUtils httpUtils = new HttpUtils(10000);
            httpUtils.configCurrentHttpCacheExpiry(5000);
            final ProgressUtil progressUtil = new ProgressUtil();
            progressUtil.ShowProgress(context, true, true, "正在上传......");
            String upImagePath = URLConstants.修改背景图片;
            RequestParams params = new RequestParams();
            params.addBodyParameter("doc", new File(imagepath));
            params.addBodyParameter("id", userid);
            params.addBodyParameter("docFilename", "data" + userid);
            httpUtils.send(HttpMethod.POST, upImagePath, params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException e, String msg) {
                            progressUtil.dismiss();
                            Toast.makeText(context, "上传失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            progressUtil.dismiss();
                            Toast.makeText(context, "上传成功！", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }


    private boolean tx_flag = false;
    int all_today_i = 1;
    String newtitle = "我的日程";
    int newopeartType = 0;//-2重要-3待办

    /**
     * 加载数据
     */
    public void loadData(int opeartType, String opeartSchID) {
        Log.e("TAG", "loadData");
        Log.e("TAG", opeartType + "-------------------------6");
        try {

            unlist.clear();
            todaylist.clear();
            tomorrowlist.clear();
            inweeklist.clear();
            outweeklist.clear();
            otherlist.clear();
            yestodaylist.clear();
            mList.clear();
            comelist.clear();

            String TYPEINDEX = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
            if (TYPEINDEX == null && TYPEINDEX.equals("")) {
                TYPEINDEX = "0";
            }
            newtitle = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPETITLE, "我的日程");
            newopeartType = Integer.valueOf(TYPEINDEX);
            if (newopeartType < 0) {
                opeartType = newopeartType;
                top_right_iv.setVisibility(View.VISIBLE);
                top_left_ric.setVisibility(View.VISIBLE);
                myschedule_title.setText(newtitle);
                Drawable drawable = context.getResources().getDrawable(R.mipmap.icon_jt_down);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                myschedule_title.setCompoundDrawables(null, null, drawable, null);
                myschedule_title.setPadding(50, 0, 0, 0);
                nongli.setTextColor(context.getResources().getColor(R.color.title0));
            } else {
                top_right_iv.setVisibility(View.GONE);
                top_left_ric.setVisibility(View.GONE);
                myschedule_title.setText(Today() + " " + Week());
                myschedule_title.setCompoundDrawables(null, null, null, null);
                myschedule_title.setPadding(0, 0, 0, 0);
                nongli.setTextColor(context.getResources().getColor(R.color.white));
            }
            add_btn_image.setVisibility(View.VISIBLE);
            switch (opeartType) {
                case -91:
                    all_today.setVisibility(View.VISIBLE);
                    all_tv.setText("全部");
                    today_tv.setText("今后");
                    opeartType = 3;
                    String uid = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPEUID, "9999991");
                    if (all_today_i == 0) {
                        otherlist = application.queryAllSchData(Integer.valueOf(uid), 0, all_today_i);
                    } else {
                        otherlist = application.queryAllSchData(Integer.valueOf(uid), 0, all_today_i);
                    }
                    mList.addAll(otherlist);
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                    outweekfag = "1";
                    top_ll_right.setVisibility(View.GONE);
                    headView.setVisibility(View.GONE);
                    add_btn_image.setVisibility(View.GONE);
                    break;
                case -1://以前
                    all_today.setVisibility(View.GONE);
                    yestodaylist = application.queryAllSchData(22, 0, 0);
                    otherlist = application.queryAllSchData(23, 0, 0);
                    opeartType = 3;
                    mList.addAll(yestodaylist);
                    mList.addAll(otherlist);
                    headView.setVisibility(View.GONE);
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                    outweekfag = "1";
                    top_ll_right.setVisibility(View.VISIBLE);
                    break;
                case -2:
                    all_today.setVisibility(View.VISIBLE);
                    headView.setVisibility(View.GONE);
                    all_tv.setText("全部");
                    today_tv.setText("今后+未结束");
                    opeartType = 3;
                    if (all_today_i == 0) {
                        otherlist = application.queryAllSchData(25, 0, 0);
                        yestodaylist = application.queryAllSchData(26, 0, 0);
                        todaylist = application.queryAllSchData(27, 0, 0);
                        tomorrowlist = application.queryAllSchData(28, 0, 0);
                        inweeklist = application.queryAllSchData(29, 0, 0);
                        outweeklist = application.queryAllSchData(30, 0, 0);
                    } else {
                        otherlist = application.queryAllSchData(31, 0, 0);
                        yestodaylist = application.queryAllSchData(32, 0, 0);
                        todaylist = application.queryAllSchData(33, 0, 0);
                        tomorrowlist = application.queryAllSchData(34, 0, 0);
                        inweeklist = application.queryAllSchData(35, 0, 0);
                        outweeklist = application.queryAllSchData(36, 0, 0);
                    }
                    Collections.sort(otherlist, new SchDateComparator());

                    mList.addAll(otherlist);
                    mList.addAll(yestodaylist);
                    mList.addAll(todaylist);
                    mList.addAll(tomorrowlist);
                    mList.addAll(inweeklist);
                    mList.addAll(outweeklist);
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                    outweekfag = "1";
                    top_ll_right.setVisibility(View.VISIBLE);
                    break;
                case -3:
                    if (all_today_i == 0) {
                        mList.addAll(application.queryAllSchData(-6, 0, 0));
                    } else {
                        mList.addAll(application.queryAllSchData(0, 0, 0));
                    }
                    all_tv.setText("全部");
                    today_tv.setText("今后+未结束");
                    all_today.setVisibility(View.VISIBLE);
                    opeartType = 3;
                    headView.setVisibility(View.GONE);
                    top_ll_right.setVisibility(View.VISIBLE);
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                    outweekfag = "1";
                    break;
                case -4:
                    all_today.setVisibility(View.VISIBLE);
                    headView.setVisibility(View.GONE);
                    all_tv.setText("全部");
                    today_tv.setText("今后+未结束");
                    opeartType = 3;

                    if (all_today_i == 0) {
                        otherlist = application.queryAllSchData(66, 0, 0);
                        yestodaylist = application.queryAllSchData(67, 0, 0);
                        todaylist = application.queryAllSchData(68, 0, 0);
                        tomorrowlist = application.queryAllSchData(69, 0, 0);
                        inweeklist = application.queryAllSchData(70, 0, 0);
                        outweeklist = application.queryAllSchData(71, 0, 0);
                    } else {
                        otherlist = application.queryAllSchData(72, 0, 0);
                        yestodaylist = application.queryAllSchData(73, 0, 0);
                        todaylist = application.queryAllSchData(74, 0, 0);
                        tomorrowlist = application.queryAllSchData(75, 0, 0);
                        inweeklist = application.queryAllSchData(76, 0, 0);
                        outweeklist = application.queryAllSchData(77, 0, 0);
                    }
                    Collections.sort(otherlist, new SchDateComparator());

                    mList.addAll(otherlist);
                    mList.addAll(yestodaylist);
                    mList.addAll(todaylist);
                    mList.addAll(tomorrowlist);
                    mList.addAll(inweeklist);
                    mList.addAll(outweeklist);
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                    outweekfag = "1";
                    top_ll_right.setVisibility(View.VISIBLE);
                    break;
                case -6:
                case -7:
                case -8:
                case -9:
                case -10:
                case -11:
                case -12:
                    opeartType = Math.abs(opeartType) - 5;
                    if (all_today_i == 0) {
                        otherlist = application.queryAllSchData(50, 0, opeartType);
                        yestodaylist = application.queryAllSchData(51, 0, opeartType);
                        todaylist = application.queryAllSchData(52, 0, opeartType);
                        tomorrowlist = application.queryAllSchData(53, 0, opeartType);
                        inweeklist = application.queryAllSchData(54, 0, opeartType);
                        outweeklist = application.queryAllSchData(55, 0, opeartType);
                    } else {
                        otherlist = application.queryAllSchData(56, 0, opeartType);
                        yestodaylist = application.queryAllSchData(57, 0, opeartType);
                        todaylist = application.queryAllSchData(58, 0, opeartType);
                        tomorrowlist = application.queryAllSchData(59, 0, opeartType);
                        inweeklist = application.queryAllSchData(60, 0, opeartType);
                        outweeklist = application.queryAllSchData(61, 0, opeartType);
                    }

                    Collections.sort(otherlist, new SchDateComparator());

                    if (all_today_i == 0) {
                        otherlist.addAll(application.queryAllSchData(50, 0, 100 + opeartType));
                        yestodaylist.addAll(application.queryAllSchData(51, 0, 100 + opeartType));
                        todaylist.addAll(application.queryAllSchData(52, 0, 100 + opeartType));
                        tomorrowlist.addAll(application.queryAllSchData(53, 0, 100 + opeartType));
                        inweeklist.addAll(application.queryAllSchData(54, 0, 100 + opeartType));
                        outweeklist.addAll(application.queryAllSchData(55, 0, 100 + opeartType));
                    } else {
                        otherlist.addAll(application.queryAllSchData(56, 0, 100 + opeartType));
                        yestodaylist.addAll(application.queryAllSchData(57, 0, 100 + opeartType));
                        todaylist.addAll(application.queryAllSchData(58, 0, 100 + opeartType));
                        tomorrowlist.addAll(application.queryAllSchData(59, 0, 100 + opeartType));
                        inweeklist.addAll(application.queryAllSchData(60, 0, 100 + opeartType));
                        outweeklist.addAll(application.queryAllSchData(61, 0, 100 + opeartType));
                    }

                    Collections.sort(otherlist, new SchDateComparator());

                    mList.addAll(otherlist);
                    mList.addAll(yestodaylist);
                    mList.addAll(todaylist);
                    mList.addAll(tomorrowlist);
                    mList.addAll(inweeklist);
                    mList.addAll(outweeklist);

                    all_tv.setText("全部");
                    today_tv.setText("今后+未结束");
                    all_today.setVisibility(View.VISIBLE);
                    headView.setVisibility(View.GONE);
                    opeartType = 3;
                    top_ll_right.setVisibility(View.VISIBLE);
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                    outweekfag = "1";
                    break;
                default:
                    all_today.setVisibility(View.GONE);
                    untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");// 0显示 1不显示
                    outweekfag = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "0");

                    String date = DateUtil.formatDateTimeSs(new Date());
                    int year = Integer.parseInt(date.substring(0, 4).toString()) - 1;
                    String beforeDownTime = String.valueOf(year) + date.substring(4, 19).toString();
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.OLDUPDATETIME, beforeDownTime);

                    int count = application.QueryGuoQiWeiJieShuCount();
                    if (count == 0 && tx_flag == false) {
                        headView.setVisibility(View.GONE);
                    } else {
                        headView.setVisibility(View.VISIBLE);
                        guoqiweijieshu_tv.setText(count + "");
                        if (count == 0 && tx_flag == true) {
                            up_down.setVisibility(View.GONE);
                            tixing_rl.setVisibility(View.VISIBLE);
                        } else if (count > 0 && tx_flag == false) {
                            up_down.setVisibility(View.VISIBLE);
                            tixing_rl.setVisibility(View.GONE);
                        } else {
                            up_down.setVisibility(View.VISIBLE);
                            tixing_rl.setVisibility(View.VISIBLE);
                        }
                    }

                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("0")) {
                        tixing_rl.setVisibility(View.GONE);
                    }


                    comelist = application.queryAllSchData(16, 0, 0);

                    if ("0".equals(untaskend)) {
                        unlist = application.queryAllSchData(90, 0, 0);
                    } else {
                        unlist = application.queryAllSchData(92, 0, 0);
                    }
                    if ("0".equals(untaskend)) {
                        todaylist = application.queryAllSchData(2, 0, 0);
                    } else {
                        todaylist = application.queryAllSchData(7, 0, 0);
                    }
                    tomorrowlist = application.queryAllSchData(3, 0, 0);
                    inweeklist = application.queryAllSchData(4, 0, 0);
                    outweeklist = application.queryAllSchData(5, 0, 0);

                    uncount = unlist.size();
                    todaycount = todaylist.size();
                    tomorrowcount = tomorrowlist.size();
                    inweekcount = inweeklist.size();
                    outweekcount = outweeklist.size();
//                    mList.addAll(unlist);
                    mList.addAll(todaylist);
                    mList.addAll(tomorrowlist);
                    mList.addAll(inweeklist);
//                    mList.addAll(outweeklist);
                    top_ll_right.setVisibility(View.VISIBLE);

                    if (uncount == 0 && todaycount == 0 && tomorrowcount == 0 && inweekcount == 0) {
                        mList.addAll(outweeklist);
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                        outweekfag = "1";
                    } else {
                        if ("1".equals(outweekfag)) {
                            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                            outweekfag = "1";
                            mList.addAll(outweeklist);
                        }
                    }

                    break;
            }
            if (headView.getVisibility() == View.VISIBLE) {
                if (tixing_rl.getVisibility() == View.VISIBLE && up_down.getVisibility() == View.VISIBLE) {
                    headView.setPadding(0, 0, 0, Utils.dipTopx(context, 10));
                } else if (tixing_rl.getVisibility() == View.VISIBLE && up_down.getVisibility() == View.GONE) {
                    headView.setPadding(0, 0, 0, Utils.dipTopx(context, 10));
                } else if (tixing_rl.getVisibility() == View.GONE && up_down.getVisibility() == View.VISIBLE) {
                    headView.setPadding(0, 0, 0, Utils.dipTopx(context, 10));
                }
            } else {
                tixing_rl.setVisibility(View.GONE);
                up_down.setVisibility(View.GONE);
                headView.setPadding(0, 0, 0, Utils.dipTopx(context, 20));
            }

            for (int i = 0; i < mList.size(); i++) {
                Map<String, String> m1 = mList.get(i);
                for (int j = i + 1; j < mList.size(); j++) {
                    Map<String, String> m2 = mList.get(j);
                    if ((m1.get(ScheduleTable.schSourceType).equals("3") && m2.get(ScheduleTable.schSourceType).equals("3")) ||
                            (m1.get(ScheduleTable.schSourceType).equals("4") && m2.get(ScheduleTable.schSourceType).equals("4")) ||
                            (m1.get(ScheduleTable.schSourceType).equals("5") && m2.get(ScheduleTable.schSourceType).equals("5"))) {
                        if (m1.get(ScheduleTable.schSourceDesc).equals(m2.get(ScheduleTable.schSourceDesc))) {
                            mList.remove(j);
                            continue;
                        }
                    }
                }
            }

            if (!opeartSchID.isEmpty()) {
                for (int i = 0; i < mList.size(); i++) {
                    if (opeartSchID.equals(mList.get(i).get(ScheduleTable.schID))) {
                        opeartPosition = i;
                        break;
                    }
                }
            }

            localpath = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");

            if (opeartType == 3) {
                setDataToAdapter();
            } else if (opeartType == 0) {
                adapter.addCalender(opeartPosition, mList.get(opeartPosition),
                        uncount, todaycount, tomorrowcount,
                        inweekcount, outweekcount, localpath, outweekfag);
//                recyclerView.setAdapter(adapter);
//                adapter.notifyDataSetChanged();
            } else if (opeartType == 1) {
                if (untaskend.equals("0")) {
                    adapter.notifyDataSetChanged();
                } else {
                    adapter.deleteCaledner(opeartPosition, uncount, todaycount, tomorrowcount,
                            inweekcount, outweekcount, localpath, outweekfag);
//                    recyclerView.setAdapter(adapter);
//                    adapter.notifyDataSetChanged();
                }

            } else if (opeartType == 2) {
                if (untaskend.equals("0")) {
                    adapter.notifyDataSetChanged();
                } else {
                    adapter.updateCalender(opeartPosition, mList.get(opeartPosition));
//                    recyclerView.setAdapter(adapter);
//                    adapter.notifyDataSetChanged();
                }
            } else {
                adapter.notifyDataSetChanged();
                adapter.noschHeaderViewAdapter();
            }

            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.IS_MONTH_RE, "1");
            loadCount();
            Log.e("TAG", "-------------------------7");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void setDataToAdapter() {

        int noEndCount = App.getDBcApplication().QueryNowGuoQiWeiJieShuCount();
        EventBus.getDefault().post(new PostSendMainActivity(1, noEndCount));

        adapter = new CalenderAdapter(getActivity(), unlist, mList, handler,
                uncount, todaycount, tomorrowcount, inweekcount, outweekcount,
                localpath, outweekfag, width, getActivity().getWindowManager());
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void isNetWork() {

        if (NetUtil.getConnectState(getActivity()) != NetWorkState.NONE) {
            Intent downRepeat = new Intent(context, DownCalenderService.class);
            downRepeat.setAction("DownCalender");
            downRepeat.putExtra("isOnRefresh", true);
            downRepeat.setPackage(context.getPackageName());
            context.startService(downRepeat);

            Intent DownCa = new Intent(context, DownCalenderNoteService.class);
            DownCa.setAction("DownCalenderNoteService");
            DownCa.setPackage(context.getPackageName());
            context.startService(DownCa);
        } else {
            return;
        }
    }

    private void UpLoadData() {
//        if (NetUtil.getConnectState(getActivity()) != NetWorkState.NONE) {
//            Intent intent = new Intent(getActivity(), UpLoadService.class);
//            intent.setAction(Const.UPLOADDATA);
//            intent.setPackage(getActivity().getPackageName());
//            getActivity().startService(intent);
//        } else {
//            return;
//        }
    }

    int sindex = -1;
    int stop = -1;


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent = null;
            final Map<String, String> mMap = (Map<String, String>) msg.obj;
            final int position = msg.arg1;
            if (msg.what < 8) {
                if (Integer.parseInt(mMap.get(ScheduleTable.schID)) < 0) {
                    if (schIDList != null && schIDList.size() > 0) {
                        for (int i = 0; i < schIDList.size(); i++) {
                            Object[] indexStr = schIDList.get(i).keySet().toArray();
                            String index = indexStr[0].toString();
                            if (Integer.parseInt(mMap.get(ScheduleTable.schID)) == Integer.parseInt(index)) {
                                mMap.put(ScheduleTable.schID, schIDList.get(i).get(index));
                                break;
                            }
                        }
                    }
                }
            }
            if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPEUID, "").isEmpty()) {

                switch (msg.what) {
                    case -1:
                        itemMore(mMap, 1, position);
//                        dialogDetailOnClick(mMap, 0, position);
                        break;
                    case -2:
                        itemMore(mMap, 0, position);
                        break;
                    case 0:// 点击菜单(详情菜单)
                        App.getDBcApplication().updateSchReadData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                        adapter.updateRead(position, msg.arg2);
                        if (mList.size() + unlist.size() > 0) {
                            Map<String, String> map = new HashMap<>();
                            if (msg.arg2 == 0) {
                                map = App.getDBcApplication().QueryhongFuData(mList.get(position).get(ScheduleTable.schRepeatID));
                            } else if (msg.arg2 == 2) {
                                map = App.getDBcApplication().QueryhongFuData(unlist.get(position).get(ScheduleTable.schRepeatID));
                            }
                            if (map != null) {
                                if (!map.get(CLRepeatTable.remark2).isEmpty()) {
                                    WBA_FindFunctionMy.ListBean bean = App.getDBcApplication().get_tb_function_my(map.get(CLRepeatTable.remark2));
                                    if (bean != null && !bean.url.isEmpty()) {
                                        Intent x = new Intent(context, WebViewActivity.class);
                                        x.putExtra("url", bean.url);
                                        x.putExtra("remark2", bean.id + "");
                                        x.putExtra("fun_id", bean.id + "");
                                        x.putExtra("schID", mMap.get(ScheduleTable.schID));
                                        startActivityForResult(x, 100);
                                    } else {
                                        detail(mMap, msg.arg2, position);
                                    }
                                } else if (map.get(CLRepeatTable.repContent).length() > 2 && map.get(CLRepeatTable.repContent).substring(0, 2).equals("#%")) {
                                    List<CalenderNoteBean.PageBean.ItemsBean> list =
                                            App.getDBcApplication().getCalenderNoteDetailData(userid, map.get(CLRepeatTable.repSourceDesc), false);
                                    if (list.size() >= 1 && UriUtils.isUrl(list.get(0).contents)) {
                                        Intent x = new Intent(context, WebViewActivity.class);
                                        x.putExtra("url", list.get(0).contents);
                                        x.putExtra("remark2", map.get(CLRepeatTable.repContent));
                                        x.putExtra("fun_id", "");
                                        x.putExtra("schID", mMap.get(ScheduleTable.schID));
                                        startActivityForResult(x, 100);
                                    } else {
                                        detail(mMap, msg.arg2, position);
                                    }
                                } else {
                                    detail(mMap, msg.arg2, position);
                                }
                            } else if (mMap.get(ScheduleTable.schRemark6) != null) {
                                WBA_FindFunctionMy.ListBean bean = App.getDBcApplication().get_tb_function_my(mMap.get(ScheduleTable.schRemark6));
                                if (bean != null && !bean.url.isEmpty()) {
                                    Intent x = new Intent(context, WebViewActivity.class);
                                    x.putExtra("url", bean.url);
                                    x.putExtra("remark2", bean.id + "");
                                    x.putExtra("fun_id", bean.id + "");
                                    x.putExtra("schID", mMap.get(ScheduleTable.schID));
                                    startActivityForResult(x, 100);
                                } else if (mMap.get(ScheduleTable.schContent).length() > 2 && mMap.get(ScheduleTable.schContent).substring(0, 2).equals("#%")) {
                                    List<CalenderNoteBean.PageBean.ItemsBean> list =
                                            App.getDBcApplication().getCalenderNoteDetailData(userid, mMap.get(ScheduleTable.schSourceDesc), false);
                                    if (list.size() >= 1 && UriUtils.isUrl(list.get(0).contents)) {
                                        Intent x = new Intent(context, WebViewActivity.class);
                                        x.putExtra("url", list.get(0).contents);
                                        x.putExtra("remark2", mMap.get(ScheduleTable.schContent));
                                        x.putExtra("schID", mMap.get(ScheduleTable.schID));
                                        x.putExtra("fun_id", "");
                                        startActivityForResult(x, 100);
                                    } else {
                                        detail(mMap, msg.arg2, position);
                                    }
                                } else {
                                    detail(mMap, msg.arg2, position);
                                }
                            } else {
                                detail(mMap, msg.arg2, position);
                            }
                        }
                        break;

                    case 2:// 设为结束deleteItem
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APPWIDGETUPLOADTYPE, "0");
                        if (msg.arg2 == 1) {
                            if (Integer.valueOf(mList.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                    && Integer.valueOf(mList.get(position).get(ScheduleTable.schAID)) == 0) {
                                if (!mList.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                }
                            } else {
                                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                            }

                            if (mList.get(position).get(ScheduleTable.schSourceType).toString().equals("3")) {
                                if (mList.get(position).get(ScheduleTable.schpisEnd).toString().equals("0")) {
                                    SixNewTaskDialog sixNewTaskDialog = new SixNewTaskDialog(context, R.style.dialog_translucent1,
                                            getActivity().getWindowManager(), 2, mList.get(position).get(ScheduleTable.schSourceDesc)
                                            , mList.get(position).get(ScheduleTable.schcRecommendId));
                                    sixNewTaskDialog.show();
                                    sixNewTaskDialog.setCallBack(new SixNewTaskDialog.CallBack() {
                                        @Override
                                        public void NewTaskDialogSure() {
                                            endCalender(mMap, position);
                                        }

                                        @Override
                                        public void NewTaskDialogCancel() {
                                            adapter.notifyDataSetChanged();
                                        }
                                    });
                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                endCalender(mMap, position);
                            }
                        } else if (msg.arg2 == 0) {
                            if (Integer.valueOf(mList.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                    && Integer.valueOf(mList.get(position).get(ScheduleTable.schAID)) == 0) {
                                if (!mList.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                    endCalender(mMap, position);
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                    if (mList.get(position).get(ScheduleTable.schSourceType).toString().equals("3")) {
                                        if (mList.get(position).get(ScheduleTable.schpisEnd).toString().equals("0")) {
                                            SixNewTaskDialog sixNewTaskDialog = new SixNewTaskDialog(context, R.style.dialog_translucent1,
                                                    getActivity().getWindowManager(), 0, mList.get(position).get(ScheduleTable.schSourceDesc)
                                                    , mList.get(position).get(ScheduleTable.schcRecommendId));
                                            sixNewTaskDialog.show();
                                            sixNewTaskDialog.setCallBack(new SixNewTaskDialog.CallBack() {
                                                @Override
                                                public void NewTaskDialogSure() {
                                                    endCalender(mMap, position);
                                                }

                                                @Override
                                                public void NewTaskDialogCancel() {
                                                    adapter.notifyDataSetChanged();
                                                }
                                            });
                                        } else {
                                            adapter.notifyDataSetChanged();
                                        }
                                    } else {
                                        deleteItem(mMap, position);
                                    }
                                }

                            } else {
                                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                endCalender(mMap, position);
                            }
                        } else if (msg.arg2 == 3) {
                            if (Integer.valueOf(unlist.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                    && Integer.valueOf(unlist.get(position).get(ScheduleTable.schAID)) == 0) {
                                if (!unlist.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                }
                            } else {
                                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                            }

                            if (unlist.get(position).get(ScheduleTable.schSourceType).toString().equals("3")) {
                                if (unlist.get(position).get(ScheduleTable.schpisEnd).toString().equals("0")) {
                                    SixNewTaskDialog sixNewTaskDialog = new SixNewTaskDialog(context, R.style.dialog_translucent1,
                                            getActivity().getWindowManager(), 2, unlist.get(position).get(ScheduleTable.schSourceDesc)
                                            , unlist.get(position).get(ScheduleTable.schcRecommendId));
                                    sixNewTaskDialog.show();
                                    sixNewTaskDialog.setCallBack(new SixNewTaskDialog.CallBack() {
                                        @Override
                                        public void NewTaskDialogSure() {
                                            endCalender(mMap, position);
                                        }

                                        @Override
                                        public void NewTaskDialogCancel() {
                                            adapter.notifyDataSetChanged();
                                        }
                                    });
                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                endCalender(mMap, position);
                            }
                        } else if (msg.arg2 == 2) {
                            if (Integer.valueOf(unlist.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                    && Integer.valueOf(unlist.get(position).get(ScheduleTable.schAID)) == 0) {
                                if (!unlist.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                    endCalender(mMap, position);
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                    if (unlist.get(position).get(ScheduleTable.schSourceType).toString().equals("3")) {
                                        if (unlist.get(position).get(ScheduleTable.schpisEnd).toString().equals("0")) {
                                            SixNewTaskDialog sixNewTaskDialog = new SixNewTaskDialog(context, R.style.dialog_translucent1,
                                                    getActivity().getWindowManager(), 0, unlist.get(position).get(ScheduleTable.schSourceDesc)
                                                    , unlist.get(position).get(ScheduleTable.schcRecommendId));
                                            sixNewTaskDialog.show();
                                            sixNewTaskDialog.setCallBack(new SixNewTaskDialog.CallBack() {
                                                @Override
                                                public void NewTaskDialogSure() {
                                                    endCalender(mMap, position);
                                                }

                                                @Override
                                                public void NewTaskDialogCancel() {
                                                    adapter.notifyDataSetChanged();
                                                }
                                            });
                                        } else {
                                            adapter.notifyDataSetChanged();
                                        }
                                    } else {
                                        deleteItem(mMap, position);
                                    }
                                }

                            } else {
                                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                endCalender(mMap, position);
                            }
                        }
                        Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentf.putExtras(extras);
                        getActivity().sendBroadcast(intentf);
//                        try {
//                            if ("0".equals(untaskend)) {
//                                unlist = application.queryAllSchData(90, 0, 0);
//                            } else {
//                                unlist = application.queryAllSchData(92, 0, 0);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                        adapter.updateHeader(unlist);
                        break;

                    case 3:// 删除
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DELETETYPE, "1");

                        try {
                            if (msg.arg2 == 0) {
                                if (Integer.valueOf(mList.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                        && Integer.valueOf(mList.get(position).get(ScheduleTable.schAID)) == 0) {
                                    if (!mList.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                        deleteCalender(mMap, 0, position);
                                    } else {
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                        if (mList.get(position).get(ScheduleTable.schSourceType).equals("3") ||
                                                mList.get(position).get(ScheduleTable.schSourceType).equals("4") ||
                                                mList.get(position).get(ScheduleTable.schSourceType).equals("5")) {
                                            SixNewTaskDialog sixNewTaskDialog = new SixNewTaskDialog(context, R.style.dialog_translucent1,
                                                    getActivity().getWindowManager(), mList.get(position).get(ScheduleTable.schSourceType).equals("3") ? 1 : 3,
                                                    mList.get(position).get(ScheduleTable.schSourceDesc)
                                                    , mList.get(position).get(ScheduleTable.schcRecommendId));
                                            sixNewTaskDialog.show();
                                            sixNewTaskDialog.setCallBack(new SixNewTaskDialog.CallBack() {
                                                @Override
                                                public void NewTaskDialogCancel() {
                                                    adapter.notifyDataSetChanged();
                                                }

                                                @Override
                                                public void NewTaskDialogSure() {
                                                    deleteCalender(mMap, 0, position);
                                                }
                                            });
                                        } else {
                                            alertDeleteDialog(mMap, 0, position);
                                        }
                                    }
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                    deleteCalender(mMap, 0, position);
                                }
                            } else if (msg.arg2 == 2) {
                                if (Integer.valueOf(unlist.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                        && Integer.valueOf(unlist.get(position).get(ScheduleTable.schAID)) == 0) {
                                    if (!unlist.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                        deleteCalender(mMap, 0, position);
                                    } else {
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                        if (unlist.get(position).get(ScheduleTable.schSourceType).equals("3") ||
                                                unlist.get(position).get(ScheduleTable.schSourceType).equals("4") ||
                                                unlist.get(position).get(ScheduleTable.schSourceType).equals("5")) {
                                            SixNewTaskDialog sixNewTaskDialog = new SixNewTaskDialog(context, R.style.dialog_translucent1,
                                                    getActivity().getWindowManager(), unlist.get(position).get(ScheduleTable.schSourceType).equals("3") ? 1 : 3,
                                                    unlist.get(position).get(ScheduleTable.schSourceDesc)
                                                    , unlist.get(position).get(ScheduleTable.schcRecommendId));
                                            sixNewTaskDialog.show();
                                            sixNewTaskDialog.setCallBack(new SixNewTaskDialog.CallBack() {
                                                @Override
                                                public void NewTaskDialogCancel() {
                                                    adapter.notifyDataSetChanged();
                                                }

                                                @Override
                                                public void NewTaskDialogSure() {
                                                    deleteCalender(mMap, 0, position);
                                                }
                                            });
                                        } else {
                                            alertDeleteDialog(mMap, 0, position);
                                        }
                                    }
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                    deleteCalender(mMap, 0, position);
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Intent intentd = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extrasd = new Bundle();
                        intentd.putExtras(extrasd);
                        getActivity().sendBroadcast(intentd);
//                        try {
//                            if ("0".equals(untaskend)) {
//                                unlist = application.queryAllSchData(90, 0, 0);
//                            } else {
//                                unlist = application.queryAllSchData(92, 0, 0);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                        adapter.updateHeader(unlist);
                        break;
                    case 4:// 跳到日历页面
                        intent = new Intent(getActivity(), DateCalendarActivity.class);
                        intent.putExtra("myschedulefragment", "0");
                        intent.putExtra("sourse", 0);
                        intent.putExtra("dateTime", mMap.get(ScheduleTable.schDate));
                        intent.putExtra("postpone", postpone);
                        intent.putExtra("openState", mMap.get(ScheduleTable.schOpenState));
                        intent.putExtra("ringcode", mMap.get(ScheduleTable.schRingCode));
                        intent.putExtra("schIsAlarm", mMap.get(ScheduleTable.schIsAlarm));
                        startActivity(intent);
                        break;
                    case 5:// 点击展开一周后
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "1");
                        mList.addAll(outweeklist);
                        adapter.notifyItemRangeChanged(0, mList.size(), 1);
                        // loadData();
                        break;
                    case 6:
                        DownFrendCalenderLy();
                        break;
                    case 7://收到的任务更多
//                        itemMore(mMap, 0, position);
//                        dialogDetailOnClick(mMap, 0, position);
                        break;
                    case 8://点击收拢
                        loadData(3, "");
                        break;
                }
            }
        }

    };

    private void detail(Map<String, String> mMap, int type, int position) {

        if (mMap.get(ScheduleTable.schSourceType).equals("3")
                || mMap.get(ScheduleTable.schSourceType).equals("4")
                || mMap.get(ScheduleTable.schSourceType).equals("5")) {
            boolean isRead = false;
            if (application.isRead(mMap.get(ScheduleTable.schID)) == -1) {
                //新清单
                isRead = true;
            }

            App.getDBcApplication().updateReadState(Integer.valueOf(mMap.get(ScheduleTable.schID)), 2);
//                            App.getDBcApplication().updateSchSourceDescSpare(mMap.get(ScheduleTable.schID));
            loadCount();
            Intent taskintent = new Intent(context, NewSixTaskDetailActivity.class);
            taskintent.putExtra("ID", mMap.get(ScheduleTable.ID));
            taskintent.putExtra("schID", mMap.get(ScheduleTable.schID));
            taskintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
            taskintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
            taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
            taskintent.putExtra("schSourceType", mMap.get(ScheduleTable.schSourceType));
            taskintent.putExtra("schCreateTime", mMap.get(ScheduleTable.schCreateTime));
            taskintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
            taskintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
            taskintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
            taskintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
            taskintent.putExtra("schcRecommendName", mMap.get(ScheduleTable.schcRecommendName));
            taskintent.putExtra("schContent", mMap.get(ScheduleTable.schContent));
            taskintent.putExtra("schcRecommendId", mMap.get(ScheduleTable.schcRecommendId));
            taskintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
            taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
            taskintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
            taskintent.putExtra("schRemark4", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark4)));
            taskintent.putExtra("schRemark5", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark5)));
            startActivityForResult(taskintent, 600);
        } else if (mMap.get(ScheduleTable.schSourceType).equals("2")) {
            boolean isRead = false;
            if (application.isRead(mMap.get(ScheduleTable.schID)) == -1) {
                //新清单
                isRead = true;
            }

            App.getDBcApplication().updateReadState(Integer.valueOf(mMap.get(ScheduleTable.schID)), 2);
//                            App.getDBcApplication().updateSchSourceDescSpare(mMap.get(ScheduleTable.schID));
            loadCount();
            if (StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)).equals("1")) {
                Intent taskintent = new Intent(context, NewSixTaskDetailActivity.class);
                taskintent.putExtra("ID", mMap.get(ScheduleTable.ID));
                taskintent.putExtra("schID", mMap.get(ScheduleTable.schID));
                taskintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
                taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                taskintent.putExtra("schSourceType", mMap.get(ScheduleTable.schSourceType));
                taskintent.putExtra("schCreateTime", mMap.get(ScheduleTable.schCreateTime));
                taskintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
                taskintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
                taskintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
                taskintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
                taskintent.putExtra("schcRecommendName", mMap.get(ScheduleTable.schcRecommendName));
                taskintent.putExtra("schContent", mMap.get(ScheduleTable.schContent));
                taskintent.putExtra("schcRecommendId", mMap.get(ScheduleTable.schcRecommendId));
                taskintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
                taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                taskintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
                taskintent.putExtra("schRemark4", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark4)));
                taskintent.putExtra("schRemark5", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark5)));
                startActivityForResult(taskintent, 600);
            } else {
                Intent cintent = new Intent(context, CalenderNoteEditActivity.class);
                cintent.putExtra("lingshengnames", mMap.get(ScheduleTable.schRingDesc));
                cintent.putExtra("lingshengcode", mMap.get(ScheduleTable.schRingCode));
                cintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
                cintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
                cintent.putExtra("schIsAlarm", mMap.get(ScheduleTable.schIsAlarm));
                cintent.putExtra("schBeforeTime", mMap.get(ScheduleTable.schBeforeTime));
                cintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
                cintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
                cintent.putExtra("content", mMap.get(ScheduleTable.schContent));
                cintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
                cintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                cintent.putExtra("schID", mMap.get(ScheduleTable.schID));
                cintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
                cintent.putExtra("schRepeatID", mMap.get(ScheduleTable.schRepeatID));
                cintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
                startActivityForResult(cintent, 600);
            }
        } else {
            if (Integer.valueOf(mMap.get(ScheduleTable.schcRecommendId)) > 0
                    && Integer.valueOf(mMap.get(ScheduleTable.schAID)) == 0) {
                if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
//                                    dialogDetailOnClick(mMap, 0, position);
                    if (Integer.valueOf(mMap.get(ScheduleTable.schcRecommendId)) >= 0 && StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)).equals("1")) {
                        Intent taskintent = new Intent(context, NewSixTaskDetailActivity.class);
                        taskintent.putExtra("ID", mMap.get(ScheduleTable.ID));
                        taskintent.putExtra("schID", mMap.get(ScheduleTable.schID));
                        taskintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
                        taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                        taskintent.putExtra("schSourceType", mMap.get(ScheduleTable.schSourceType));
                        taskintent.putExtra("schCreateTime", mMap.get(ScheduleTable.schCreateTime));
                        taskintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
                        taskintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
                        taskintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
                        taskintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
                        taskintent.putExtra("schcRecommendName", mMap.get(ScheduleTable.schcRecommendName));
                        taskintent.putExtra("schContent", mMap.get(ScheduleTable.schContent));
                        taskintent.putExtra("schcRecommendId", mMap.get(ScheduleTable.schcRecommendId));
                        taskintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
                        taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                        taskintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
                        taskintent.putExtra("schRemark4", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark4)));
                        taskintent.putExtra("schRemark5", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark5)));
                        startActivityForResult(taskintent, 600);
                    } else {
                        Intent cintent = new Intent(context, CalenderNoteEditActivity.class);
                        cintent.putExtra("lingshengnames", mMap.get(ScheduleTable.schRingDesc));
                        cintent.putExtra("lingshengcode", mMap.get(ScheduleTable.schRingCode));
                        cintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
                        cintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
                        cintent.putExtra("schIsAlarm", mMap.get(ScheduleTable.schIsAlarm));
                        cintent.putExtra("schBeforeTime", mMap.get(ScheduleTable.schBeforeTime));
                        cintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
                        cintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
                        cintent.putExtra("content", mMap.get(ScheduleTable.schContent));
                        cintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
                        cintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                        cintent.putExtra("schID", mMap.get(ScheduleTable.schID));
                        cintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
                        cintent.putExtra("schRepeatID", mMap.get(ScheduleTable.schRepeatID));
                        cintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
                        startActivityForResult(cintent, 600);
                    }
                } else {
                    if (!mMap.get(ScheduleTable.schSourceDesc).isEmpty()) {
                        boolean isRead = false;
                        if (application.isRead(mMap.get(ScheduleTable.schID)) == -1) {
                            //新清单
                            isRead = true;
                        }

                        App.getDBcApplication().updateReadState(Integer.valueOf(mMap.get(ScheduleTable.schID)), 2);
                        App.getDBcApplication().updateSchSourceDescSpare(mMap.get(ScheduleTable.schID));
                        loadCount();
                        NoteTitleDetailBean.TDelListBean bean = App.getDBcApplication().getOneNoteTitlesData(userid, mMap.get(ScheduleTable.schSourceDesc), true);
                        if (bean.titles != null) {
                            Intent intent = new Intent(context, NoteEditActivity.class);
                            intent.putExtra("qdlistenter", false);
                            intent.putExtra("titleid", "" + bean.titleId);
                            intent.putExtra("path", "" + bean.imgPath);
                            intent.putExtra("id", bean.id);
                            intent.putExtra("title", bean.titles);
                            intent.putExtra("ltype", bean.ltype + "");
                            intent.putExtra("styles", bean.styles);
                            intent.putExtra("copys", bean.copys);
                            intent.putExtra("remark", bean.remark);
                            intent.putExtra("remark1", bean.remark1);
                            intent.putExtra("openState", bean.openState);
                            intent.putExtra("type", 0);
                            startActivityForResult(intent, 100);
                        } else {
                            Intent intentfx = new Intent(context, QDFXDetailActivity.class);
                            intentfx.putExtra("title", mMap.get(ScheduleTable.schContent));
                            intentfx.putExtra("titleId", mMap.get(ScheduleTable.schSourceDesc));
                            intentfx.putExtra("path", "");
                            intentfx.putExtra("goodNum", "0");
                            intentfx.putExtra("redNum", "0");
                            intentfx.putExtra("name", mMap.get(ScheduleTable.schcRecommendName));
                            intentfx.putExtra("time", mMap.get(ScheduleTable.schCreateTime));
                            intentfx.putExtra("num", "0");
                            intentfx.putExtra("uid", mMap.get(ScheduleTable.schcRecommendId));
                            intentfx.putExtra("stylee", 0);
                            if (mMap.get(ScheduleTable.schSourceType).equals("1")) {
                                intentfx.putExtra("type", 5);
                            } else {
                                intentfx.putExtra("type", 2);
                            }
                            if (isRead) {
                                intentfx.putExtra("isRead", 1);
                            }
                            startActivityForResult(intentfx, 100);
                        }
                    } else {
                        updateFrendsPostState(mMap.get(ScheduleTable.schID));
                        App.getDBcApplication().updateReadState1(Integer.parseInt(mMap.get(ScheduleTable.schID)));
                        Intent intent1 = new Intent(getActivity(), FrendLyActivity.class);
                        intent1.putExtra("types", 1);

                        MySchBean mySchBean = new MySchBean();
                        mySchBean.schID = mMap.get(ScheduleTable.schID);
                        mySchBean.schContent = mMap.get(ScheduleTable.schContent);
                        mySchBean.schDate = mMap.get(ScheduleTable.schDate);
                        mySchBean.schTime = mMap.get(ScheduleTable.schTime);
                        mySchBean.schIsAlarm = mMap.get(ScheduleTable.schIsAlarm);
                        mySchBean.schBeforeTime = mMap.get(ScheduleTable.schBeforeTime);
                        mySchBean.schDisplayTime = mMap.get(ScheduleTable.schDisplayTime);
                        mySchBean.schIsPostpone = mMap.get(ScheduleTable.schIsPostpone);
                        mySchBean.schIsImportant = mMap.get(ScheduleTable.schIsImportant);
                        mySchBean.schColorType = mMap.get(ScheduleTable.schColorType);
                        mySchBean.schIsEnd = mMap.get(ScheduleTable.schIsEnd);
                        mySchBean.schCreateTime = mMap.get(ScheduleTable.schCreateTime);
                        mySchBean.schTags = mMap.get(ScheduleTable.schTags);
                        mySchBean.schSourceType = mMap.get(ScheduleTable.schSourceType);
                        mySchBean.schSourceDesc = mMap.get(ScheduleTable.schSourceDesc);
                        mySchBean.schSourceDescSpare = mMap
                                .get(ScheduleTable.schSourceDescSpare);
                        mySchBean.schRepeatID = mMap.get(ScheduleTable.schRepeatID);
                        mySchBean.schRepeatDate = mMap.get(ScheduleTable.schRepeatDate);
                        mySchBean.schUpdateTime = mMap.get(ScheduleTable.schUpdateTime);
                        mySchBean.schUpdateState = mMap.get(ScheduleTable.schUpdateState);
                        mySchBean.schOpenState = mMap.get(ScheduleTable.schOpenState);
                        mySchBean.schRepeatLink = mMap.get(ScheduleTable.schRepeatLink);
                        mySchBean.schRingDesc = mMap.get(ScheduleTable.schRingDesc);
                        mySchBean.schRingCode = mMap.get(ScheduleTable.schRingCode);
                        mySchBean.schcRecommendName = mMap
                                .get(ScheduleTable.schcRecommendName);
                        mySchBean.schRead = mMap.get(ScheduleTable.schRead);
                        intent1.putExtra("bean", mySchBean);
                        intent1.putExtra("schFriendID", mMap.get(ScheduleTable.schcRecommendId));
                        getActivity().startActivityForResult(intent1, 100);
                    }
                }
//                        tixing_rl.setVisibility(View.GONE);
            } else {
                if (!mMap.get(ScheduleTable.schSourceDesc).isEmpty()) {
                    boolean isRead = false;
                    if (application.isRead(mMap.get(ScheduleTable.schID)) == -1) {
                        //新清单
                        isRead = true;
                    }
                    App.getDBcApplication().updateReadState(Integer.valueOf(mMap.get(ScheduleTable.schID)), 2);
                    App.getDBcApplication().updateSchSourceDescSpare(mMap.get(ScheduleTable.schID));
                    loadCount();
                    NoteTitleDetailBean.TDelListBean bean = App.getDBcApplication().getOneNoteTitlesData(userid, mMap.get(ScheduleTable.schSourceDesc), true);
                    if (bean.titles != null) {
                        Intent intent = new Intent(context, NoteEditActivity.class);
                        intent.putExtra("qdlistenter", false);
                        intent.putExtra("titleid", "" + bean.titleId);
                        intent.putExtra("path", "" + bean.imgPath);
                        intent.putExtra("id", bean.id);
                        intent.putExtra("title", bean.titles);
                        intent.putExtra("ltype", bean.ltype + "");
                        intent.putExtra("styles", bean.styles);
                        intent.putExtra("copys", bean.copys);
                        intent.putExtra("remark", bean.remark);
                        intent.putExtra("remark1", bean.remark1);
                        intent.putExtra("openState", bean.openState);
                        intent.putExtra("type", 0);
                        startActivityForResult(intent, 100);
                    } else {
                        Intent intentfx = new Intent(context, QDFXDetailActivity.class);
                        intentfx.putExtra("title", mMap.get(ScheduleTable.schContent));
                        intentfx.putExtra("titleId", mMap.get(ScheduleTable.schSourceDesc));
                        intentfx.putExtra("path", "");
                        intentfx.putExtra("goodNum", "0");
                        intentfx.putExtra("redNum", "0");
                        intentfx.putExtra("name", mMap.get(ScheduleTable.schcRecommendName));
                        intentfx.putExtra("time", mMap.get(ScheduleTable.schCreateTime));
                        intentfx.putExtra("num", "0");
                        if (mMap.get(ScheduleTable.schSourceType).equals("1")) {
                            intentfx.putExtra("type", 5);
                        } else {
                            intentfx.putExtra("type", 2);
                        }
                        if (isRead) {
                            intentfx.putExtra("isRead", 1);
                        }
                        intentfx.putExtra("uid", mMap.get(ScheduleTable.schcRecommendId));
                        intentfx.putExtra("stylee", 0);
                        startActivityForResult(intentfx, 100);
                    }
                } else {
//                                    dialogDetailOnClick(mMap, 0, position);
                    boolean isRead = false;
                    if (application.isRead(mMap.get(ScheduleTable.schID)) == -1) {
                        //新清单
                        isRead = true;
                    }

                    App.getDBcApplication().updateReadState(Integer.valueOf(mMap.get(ScheduleTable.schID)), 2);
//                                    App.getDBcApplication().updateSchSourceDescSpare(mMap.get(ScheduleTable.schID));
                    loadCount();
                    if (Integer.valueOf(mMap.get(ScheduleTable.schcRecommendId)) >= 0 && StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)).equals("1")) {
                        Intent taskintent = new Intent(context, NewSixTaskDetailActivity.class);
                        taskintent.putExtra("ID", mMap.get(ScheduleTable.ID));
                        taskintent.putExtra("schID", mMap.get(ScheduleTable.schID));
                        taskintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
                        taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                        taskintent.putExtra("schSourceType", mMap.get(ScheduleTable.schSourceType));
                        taskintent.putExtra("schCreateTime", mMap.get(ScheduleTable.schCreateTime));
                        taskintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
                        taskintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
                        taskintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
                        taskintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
                        taskintent.putExtra("schcRecommendName", mMap.get(ScheduleTable.schcRecommendName));
                        taskintent.putExtra("schContent", mMap.get(ScheduleTable.schContent));
                        taskintent.putExtra("schcRecommendId", mMap.get(ScheduleTable.schcRecommendId));
                        taskintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
                        taskintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                        taskintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
                        taskintent.putExtra("schRemark4", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark4)));
                        taskintent.putExtra("schRemark5", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark5)));
                        startActivityForResult(taskintent, 600);
                    } else {
                        Intent cintent = new Intent(context, CalenderNoteEditActivity.class);
                        cintent.putExtra("lingshengnames", mMap.get(ScheduleTable.schRingDesc));
                        cintent.putExtra("lingshengcode", mMap.get(ScheduleTable.schRingCode));
                        cintent.putExtra("schTime", mMap.get(ScheduleTable.schTime));
                        cintent.putExtra("schDate", mMap.get(ScheduleTable.schDate));
                        cintent.putExtra("schIsAlarm", mMap.get(ScheduleTable.schIsAlarm));
                        cintent.putExtra("schBeforeTime", mMap.get(ScheduleTable.schBeforeTime));
                        cintent.putExtra("schDisplayTime", mMap.get(ScheduleTable.schDisplayTime));
                        cintent.putExtra("schIsPostpone", mMap.get(ScheduleTable.schIsPostpone));
                        cintent.putExtra("content", mMap.get(ScheduleTable.schContent));
                        cintent.putExtra("schSourceDesc", mMap.get(ScheduleTable.schSourceDesc));
                        cintent.putExtra("schImagePath", mMap.get(ScheduleTable.schImagePath));
                        cintent.putExtra("schID", mMap.get(ScheduleTable.schID));
                        cintent.putExtra("schIsEnd", mMap.get(ScheduleTable.schIsEnd));
                        cintent.putExtra("schRepeatID", mMap.get(ScheduleTable.schRepeatID));
                        cintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)));
                        startActivityForResult(cintent, 600);
                    }
                }
            }
        }
    }


    /**
     * 结束日程
     */
    private void deleteItem(final Map<String, String> mMap, final int position) {
        final AlertDialog builder = new AlertDialog.Builder(context)
                .create();

        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alterdelete);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_canel = (TextView) window
                .findViewById(R.id.delete_canel);
        delete_canel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                adapter.notifyDataSetChanged();
                builder.dismiss();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);

        delete_tv.setText("确定要结束此日程吗?");

        delete_ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                endCalender(mMap, position);
                builder.dismiss();
            }
        });
    }

    private void endCalender(Map<String, String> mMap, int position) {
        try {
            if ("0".equals(mMap.get(ScheduleTable.schIsEnd))) {
                soundstate = sharedPrefUtil.getString(getActivity(),
                        ShareFile.USERFILE, ShareFile.ENDSOUNDSTATE,
                        "0");
                wakestate = sharedPrefUtil
                        .getString(getActivity(), ShareFile.USERFILE,
                                ShareFile.ENDWAKESTATE, "0");
                if ("0".equals(soundstate)) {
                    MediaPlayer mediaPlayer = mediaPlayer = new MediaPlayer();
                    AssetFileDescriptor fileDescriptor = getActivity()
                            .getAssets().openFd("complete.mp3");
                    mediaPlayer.setDataSource(
                            fileDescriptor.getFileDescriptor(),
                            fileDescriptor.getStartOffset(),
                            fileDescriptor.getLength());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
                if ("0".equals(wakestate)) {
                    long[] pattern = {100, 400}; // 停止 开启 停止 开启
                    vibrator.vibrate(pattern, -1); // 重复两次上面的pattern
                    // 如果只想震动一次，index设为-1
                }
            }
            if ("0".equals(mMap.get(ScheduleTable.schRepeatID))) {
                updateScheduleRead1(mMap, ScheduleTable.schRead);
            } else {
                updateScheduleRead2(mMap, ScheduleTable.schRead,
                        ScheduleTable.schRepeatLink);
            }
            updateScheduleIsEnd(mMap, ScheduleTable.schIsEnd, ScheduleTable.schUpdateState);
            updateSchClock(mMap, LocateAllNoticeTable.isEnd);
            QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ENDUPDATETIME, DateUtil.formatDateTimeSs(new Date()));
            loadData(2, mMap.get(ScheduleTable.schID));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.myschedule_ll:
            case R.id.nongli:
//                intent = new Intent(getActivity(), DateCalendarActivity.class);
//                intent.putExtra("myschedulefragment", "0");
//                intent.putExtra("sourse", 0);
//                intent.putExtra("dateTime", DateUtil.nowTodyTime());
//                intent.putExtra("postpone", postpone);
//                intent.putExtra("openState", "0");
//                intent.putExtra("ringcode", "g_88");
//                intent.putExtra("schIsAlarm", "1");
//                startActivity(intent);
//                startActivityForResult(new Intent(getActivity(), TagSerachActivity.class), 100);
//                String dbpath = "/data/data/com.mission.schedule/databases/data";
//                uploadJvBaoContent(dbpath);

                CalenderTopCenterDialog dialog = new CalenderTopCenterDialog(getActivity(), R.style.dialog_translucent_top, getActivity().getWindowManager());
                dialog.show();
                dialog.setCallBack(new CalenderTopCenterDialog.CallBack() {
                    @Override
                    public void setType(int index, String title) {
                        if (index == 0) {
                            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
                        } else {
                            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "0");
                        }
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, index + "");
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPETITLE, title);
                        loadData(3, "");
                        MainActivity.instance.setmainbg();
                    }
                });
                break;
            case R.id.top_ll_right:
//                dialogOnClick();
                String TYPEINDEX = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
                int newopeartType = Integer.valueOf(TYPEINDEX);
                if (newopeartType < 0) {
                    ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    if (clipboardManager.getText() == null) {
                        alertClipIsEmptry();
                    } else {
                        String titleId = DateUtil.nowTime2();
                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        String content = clipboardManager.getText().toString();
                        if (content.length() > 1) {
                            if (content.substring(0, 2).equals("**")) {
                                String[] notecontent = content.substring(1, content.length()).split("\\*");
                                if (notecontent.length >= 2) {
                                    String[] conde = notecontent[notecontent.length - 1].split("\n");
                                    String title = notecontent[0];
                                    for (int i = 0; i < notecontent.length - 1; i++) {
                                        if (!notecontent[i].isEmpty()) {
                                            title = notecontent[i];
                                        }
                                    }
                                    String before = sharedPrefUtil.getString(context,
                                            ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
                                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                                    App.getDBcApplication().insertScheduleData(title, DateUtil.formatDate(new Date()),
                                            DateUtil.formatDateTimeHm(new Date()), 1,
                                            Integer.parseInt(before), 0, 1, 0,
                                            0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                            titleId, "", 0, "", DateUtil.formatDateTime(new Date()),
                                            1, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "",
                                            "", 0, 0, 0, 0, "", "0", "0");
                                    int i = 0;
                                    for (String item : conde) {
                                        if (!item.isEmpty()) {
                                            debean(titleId, i, item, title, false);
                                            i++;
                                        } else {
                                            continue;
                                        }
                                    }
                                } else if (notecontent.length == 1) {
                                    String before = sharedPrefUtil.getString(context,
                                            ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
                                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                                    App.getDBcApplication().insertScheduleData(notecontent[0], DateUtil.formatDate(new Date()),
                                            DateUtil.formatDateTimeHm(new Date()), 1,
                                            Integer.parseInt(before), 0, 1, 0,
                                            0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                            titleId, "", 0, "", DateUtil.formatDateTime(new Date()),
                                            1, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "",
                                            "", 0, 0, 0, 0, "", "0", "0");
                                }
                            } else {
                                String[] conde = content.split("\n");
                                String before = sharedPrefUtil.getString(context,
                                        ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
                                sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                                App.getDBcApplication().insertScheduleData(conde[0], DateUtil.formatDate(new Date()),
                                        DateUtil.formatDateTimeHm(new Date()), 1,
                                        Integer.parseInt(before), 0, 1, 0,
                                        0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                        titleId, "", 0, "", DateUtil.formatDateTime(new Date()),
                                        1, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "",
                                        "", 0, 0, 0, 0, "", "0", "0");
                                if (conde.length > 2) {
                                    int i = 0;
                                    for (int j = 1; j < conde.length; j++) {
                                        if (!conde[j].isEmpty()) {
                                            debean(titleId, i, conde[j], conde[0], true);
                                            i++;
                                        } else {
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                        loadData(0, schID + "");
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                        UpLoadData();
                    }
//                    Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//                    Bundle extras = new Bundle();
//                    intentappwidget.putExtras(extras);
//                    getActivity().sendBroadcast(intentappwidget);
                }
                break;
            case R.id.add_btn_image:
//                dialogOnClick();
//                dialogDaiBan();
                if (popupWindow != null) {
                    boolean showing = popupWindow.isShowing();
                    if (showing) {
                        popupWindow.dismiss();
                    } else {
                        addBtnImageButton();
                    }
                } else {
                    addBtnImageButton();
                }
//                intent = new Intent(context, CalenderNoteEditActivity.class);
//                intent.putExtra("newadd", true);
//                intent.putExtra("newopeartType", newopeartType);
//                startActivityForResult(intent, 600);
                break;
            case R.id.top_ll_left:
                // toggle();
//                alterImportantDialog();
//                intent = new Intent(context, NewMyAppSetActivity.class);
//                context.startActivity(intent);
                String TYPEINDEXs = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
                int newopeartTypes = Integer.valueOf(TYPEINDEXs);
                if (newopeartTypes < 0) {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPETITLE, "我的日程");
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPEUID, "");
                    loadData(3, "");
                    MainActivity.instance.setmainbg();
                }
//                else {
//                    dialogOnClick();
//                }
                break;
            case R.id.iv_more_down:
                alterImportantDialog();
                break;
            case R.id.up_down:
                startActivityForResult(new Intent(getActivity(), GuoQiWeiJieShuActivity.class), 100);
                break;
            case R.id.tixing_rl:
                tixing_rl.setVisibility(View.GONE);
                onRefreshs();
                Intent newif = new Intent(getActivity(), NewInformationActivity.class);
                newif.putExtra("type", 1);
                startActivityForResult(newif, 100);
                break;
            default:
                break;
        }
    }

    private void alertDeleteDialog(final Map<String, String> mMap,
                                   final int type, final int position) {
        final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();
        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alterdelete);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        delete_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
                if (mMap.get(ScheduleTable.schSourceType).equals("4") || mMap.get(ScheduleTable.schSourceType).equals("5")) {
                    ShareUrlDelete(mMap, false);
                }
                deleteCalender(mMap, type, position);
            }
        });
        TextView delete_canel = (TextView) window.findViewById(R.id.delete_canel);
        delete_canel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        if (type == 0) {
            delete_tv.setText("确定要删除此记事吗?");
        } else {
            delete_tv.setText("结束今天之前所有未结束的记事?");
        }

    }

    /**
     * 接收方删除链接
     *
     * @param mMap
     */
    private void ShareUrlDelete(final Map<String, String> mMap, boolean isMy) {
        try {
            final JSONObject data = new JSONObject();
            JSONArray timetable = new JSONArray();
            JSONObject json = new JSONObject();
            if (isMy) {
                json.put("updateState", 3);
                json.put("uid", "");
                json.put("puid", userid);
                json.put("pname", sharedPrefUtil.getString(ShareFile.USERNAME, ""));
            } else {
                json.put("updateState", 4);
                json.put("uid", userid);
                json.put("puid", mMap.get(ScheduleTable.schcRecommendId));
                json.put("pname", mMap.get(ScheduleTable.schcRecommendName));
            }
            json.put("ptitleimg", mMap.get(ScheduleTable.schImagePath));
            json.put("titleId", mMap.get(ScheduleTable.schSourceDesc));
            json.put("cdate", mMap.get(ScheduleTable.schDate));
            json.put("ctime", mMap.get(ScheduleTable.schTime));
            json.put("content", mMap.get(ScheduleTable.schContent));
            json.put("cisEnd", mMap.get(ScheduleTable.schIsEnd));
            json.put("cDisplayAlarm", mMap.get(ScheduleTable.schDisplayTime));
            json.put("cIsAlarm", mMap.get(ScheduleTable.schIsAlarm));
            json.put("cbefortime", mMap.get(ScheduleTable.schBeforeTime));
            json.put("cAlarmsound", mMap.get(ScheduleTable.schRingCode));
            json.put("cAlarmsoundDesc", mMap.get(ScheduleTable.schRingDesc));
            json.put("cPostpone", mMap.get(ScheduleTable.schIsPostpone));
            json.put("cImportant", mMap.get(ScheduleTable.schIsImportant));
            json.put("cscore", "0");
            json.put("changeTime", DateUtil.nowTime());
            json.put("createTime", DateUtil.nowTime());
            json.put("remark", "");
            json.put("remark1", "");
            json.put("remark2", "");
            json.put("remark3", "");
            json.put("remark4", "");
            json.put("remark5", "");
            timetable.put(json);
            data.put("timetable", timetable);


            StringRequest request4 = new StringRequest(Method.POST, URLConstants.同步临时表数据, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                }


            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("data", data.toString());
                    return map;
                }
            };
            request4.setTag("同步临时表数据");
            request4.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 1.0f));
            App.getHttpQueues().add(request4);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void deleteCalender(Map<String, String> mMap, int type, final int position) {
        if (type == 0) {
            if (StringUtils.getIsStringEqulesNull(mMap.get(ScheduleTable.schRemark1)).equals("1")) {
                ShareUrlDelete(mMap, true);
            }
            if (Integer.parseInt(mMap.get(ScheduleTable.schID)) < 0) {
                if (schIDList != null && schIDList.size() > 0) {
                    for (int i = 0; i < schIDList.size(); i++) {
                        Object[] indexStr = schIDList.get(i).keySet().toArray();
                        String index = indexStr[0].toString();
                        if (Integer.parseInt(mMap.get(ScheduleTable.schID)) == Integer.parseInt(index)) {
                            mMap.put(ScheduleTable.schID, schIDList.get(i).get(index));
                            break;
                        }
                    }
                }
            }
            try {
                String deleteId = mMap.get(ScheduleTable.schID);
                App dbContextExtended = App.getDBcApplication();
                dbContextExtended.deleteScheduleLocalData(deleteId);
                if (mMap.get(ScheduleTable.schRemark1) != null && mMap.get(ScheduleTable.schRemark1).equals("1")) {
                    dbContextExtended.updateScheduleLocalDataschRemark3(deleteId);
                } else {
                    dbContextExtended.deleteScheduleLocalData(deleteId);
                }
                dbContextExtended.deleteSch(Integer.parseInt(deleteId));

                updateDeleteScheduleRead(mMap, ScheduleTable.schRead, ScheduleTable.schRepeatLink);
                updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                if (Integer.valueOf(mMap.get(ScheduleTable.schRepeatID)) < 1) {
                    List<CalenderNoteBean.PageBean.ItemsBean> itemsBeanList =
                            App.getDBcApplication().getCalenderNoteDetailData(userid, mMap.get(ScheduleTable.schSourceDesc), false);
                    for (CalenderNoteBean.PageBean.ItemsBean bean : itemsBeanList) {
                        int state = App.getDBcApplication().getCalenderNoteDetailState(bean.titleId, userid, bean.id);
                        if (!mMap.get(ScheduleTable.schRemark1).equals("1")) {
                            App.getDBcApplication().deleteCalenderNoteDetail(bean.id, mMap.get(ScheduleTable.schSourceDesc), userid, state == 1);
                        }
                    }
                }

                String TYPEINDEX = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
                int newopeartType = Integer.valueOf(TYPEINDEX);

                loadData(1, mMap.get(ScheduleTable.schID));
                UpLoadData();

                if (newopeartType >= 0) {
                    if (mList != null && mList.size() == 0) {
                        mList = application.queryAllSchData(5, 0, 0);
                        adapter = new CalenderAdapter(context, unlist, mList, handler, 0, 0, 0, 0, mList.size(), localpath, "1", width, getActivity().getWindowManager());
                        recyclerView.setAdapter(adapter);
                    }
                }
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    MediaPlayer mediaPlayer = new MediaPlayer();
    AssetFileDescriptor fileDescriptor = null;

    /**
     * 普通记事点击弹出详情菜单 setType 0,菜单详情 1,设置
     *
     * @param mMaps
     */
    private void dialogDetailOnClick(Map<String, String> mMaps, int setType, final int position) {
        final Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
//        params.alpha = 0.93f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_calender_new_detail, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth() - 30;
        dialog.show();

        final Map<String, String> mMap = mMaps;


        List<View> viewList = new ArrayList<View>();


        MyViewPager myViewPager = (MyViewPager) more_pop_menu.findViewById(R.id.viewpager_detail);

        View viewOne = LayoutInflater.from(context).inflate(R.layout.dialog_calender_new_detail_item1, null);
        View viewTwo = LayoutInflater.from(context).inflate(R.layout.dialog_calender_new_detail_item2, null);
//        applyBlur(viewOne);
//        applyBlur(viewTwo);

        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String today = DateUtil.formatDate(calendar.getTime());
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.get(Calendar.DAY_OF_MONTH) + 1);
        String tomorrow = DateUtil.formatDate(calendar.getTime());

        final int id = Integer.parseInt(mMap.get(ScheduleTable.schID));


        final Map<String, String> map = App.getDBcApplication().QueryStateData(
                Integer.parseInt(mMap.get(ScheduleTable.schRepeatID)));

        final Intent intent = new Intent();

        final MySchBean mySchBean = new MySchBean();
        mySchBean.schID = mMap.get(ScheduleTable.schID);
        mySchBean.schContent = mMap.get(ScheduleTable.schContent);
        mySchBean.schDate = mMap.get(ScheduleTable.schDate);
        mySchBean.schTime = mMap.get(ScheduleTable.schTime);
        mySchBean.schIsAlarm = mMap.get(ScheduleTable.schIsAlarm);
        mySchBean.schBeforeTime = mMap.get(ScheduleTable.schBeforeTime);
        mySchBean.schDisplayTime = mMap.get(ScheduleTable.schDisplayTime);
        mySchBean.schIsPostpone = mMap.get(ScheduleTable.schIsPostpone);
        mySchBean.schIsImportant = mMap.get(ScheduleTable.schIsImportant);
        mySchBean.schColorType = mMap.get(ScheduleTable.schColorType);
        mySchBean.schIsEnd = mMap.get(ScheduleTable.schIsEnd);
        mySchBean.schCreateTime = mMap.get(ScheduleTable.schCreateTime);
        mySchBean.schTags = mMap.get(ScheduleTable.schTags);
        mySchBean.schSourceType = mMap.get(ScheduleTable.schSourceType);
        mySchBean.schSourceDesc = mMap.get(ScheduleTable.schSourceDesc);
        mySchBean.schSourceDescSpare = mMap.get(ScheduleTable.schSourceDescSpare);
        mySchBean.schRepeatID = mMap.get(ScheduleTable.schRepeatID);
        mySchBean.schRepeatDate = mMap.get(ScheduleTable.schRepeatDate);
        mySchBean.schUpdateTime = mMap.get(ScheduleTable.schUpdateTime);
        mySchBean.schUpdateState = mMap.get(ScheduleTable.schUpdateState);
        mySchBean.schOpenState = mMap.get(ScheduleTable.schOpenState);
        mySchBean.schRepeatLink = mMap.get(ScheduleTable.schRepeatLink);
        mySchBean.schRingDesc = mMap.get(ScheduleTable.schRingDesc);
        mySchBean.schRingCode = mMap.get(ScheduleTable.schRingCode);
        mySchBean.schcRecommendName = mMap.get(ScheduleTable.schcRecommendName);
        mySchBean.schRead = mMap.get(ScheduleTable.schRead);

        /*****第一页****/

        final TextView fenlei = viewOne.findViewById(R.id.fenlei);
        final TextView day = viewOne.findViewById(R.id.day);
        final TextView week = viewOne.findViewById(R.id.week);
        final TextView month = viewOne.findViewById(R.id.month);
        final TextView copy_content = viewOne.findViewById(R.id.copy_content);

        final LinearLayout zhuanfa = viewOne.findViewById(R.id.zhuanfa);
        final TextView color_tv = viewOne.findViewById(R.id.color_tv);
        int colortype = Integer.parseInt(mMap.get(ScheduleTable.schColorType));
        final String colorname = application.QueryTagNameData(colortype).get("ctgText");

        final TextView st_ll = viewOne.findViewById(R.id.st_ll);
        final LinearLayout stl = viewOne.findViewById(R.id.stl);
        final LinearLayout copy_ll = viewOne.findViewById(R.id.copy_ll);
        final LinearLayout time_ll = viewOne.findViewById(R.id.time_ll);
        if (mMap.get(ScheduleTable.schSourceType).equals("3")
                || mMap.get(ScheduleTable.schSourceType).equals("4")
                || mMap.get(ScheduleTable.schSourceType).equals("5")) {
//            copy_ll.setVisibility(View.GONE);
            time_ll.setVisibility(View.GONE);
//            zhuanfa.setVisibility(View.GONE);
            stl.setVisibility(View.VISIBLE);
        }
        if ("0".equals(mMap.get(ScheduleTable.schIsImportant))) {
            st_ll.setText("设为重要");
        } else {
            st_ll.setText("取消重要");
        }
        if (colorname.equals("未分类")) {
            fenlei.setText("\"" + colorname + "\"\n分类设置");
        } else {
            fenlei.setText("\"" + colorname + "\"\n分类设置");
        }

        if (mMap.get(ScheduleTable.schDate).compareTo(DateUtil.nowTodyTime()) <= 0) {
            day.setText("推到明天");
            week.setText("推到下周");
            month.setText("推到下月");
        } else {
            day.setText("推后一天");
            week.setText("推后一周");
            month.setText("推后一月");
        }
        color_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                CalenderColorDialog colorDialog = new CalenderColorDialog(context, R.style.dialog_translucent,
                        getActivity().getWindowManager(), mMap.get(ScheduleTable.schID), 1);
                colorDialog.show();
                colorDialog.setCallBack(new CalenderColorDialog.CallBack() {
                    @Override
                    public void reminderEditTime(String color_position_f, String color_position) {
                        loadData(2, mMap.get(ScheduleTable.schID));
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        });
        day.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                    String date = inWeekUtils.AfterOneDay(mMap.get(ScheduleTable.schDate));
                    App.getDBcApplication().updateScheduleDateData(id, date, mMap.get(ScheduleTable.schTime));
                    App.getDBcApplication().updateSchReadData(
                            Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    App.getDBcApplication().updateSchRepeatLinkData(
                            Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    if (!"".equals(mMap.get(ScheduleTable.schRepeatDate))
                            || !"0".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                        if (map != null) {
                            String repdate = mMap
                                    .get(ScheduleTable.schRepeatDate);
                            String lastdate = StringUtils.getIsStringEqulesNull(map
                                    .get(CLRepeatTable.repDateOne));
                            String nextdate = StringUtils.getIsStringEqulesNull(map
                                    .get(CLRepeatTable.repDateTwo));
                            repeatSetChildEndUtils.setParentState(Integer.parseInt(mMap
                                    .get(ScheduleTable.schRepeatID)), repdate, nextdate, lastdate, map);
                        }
                    }
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, mMap.get(ScheduleTable.schID));
                    loadData(4, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();

                    Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras = new Bundle();
                    intentf.putExtras(extras);
                    getActivity().sendBroadcast(intentf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        week.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                    String date = inWeekUtils.AfterOneWeek(mMap.get(ScheduleTable.schDate));
                    App.getDBcApplication().updateScheduleDateData(id, date,
                            mMap.get(ScheduleTable.schTime));
                    App.getDBcApplication().updateSchReadData(
                            Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    App.getDBcApplication().updateSchRepeatLinkData(
                            Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
//                    if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
////                        App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
//                        Map<String, String> maprepeat = App.getDBcApplication().QueryhongFuData(mMap.get(ScheduleTable.schRepeatID));
//                        if (maprepeat != null) {
//                            if ("0".equals(maprepeat.get(CLRepeatTable.repInSTable))
//                                    && "0".equals(maprepeat.get(CLRepeatTable.repIsPuase))) {
//
//                                if (application.queryChildRepeatIsSave(
//                                        maprepeat.get(CLRepeatTable.repContent),
//                                        maprepeat.get(CLRepeatTable.repNextCreatedTime),
//                                        maprepeat.get(CLRepeatTable.repID)) == false) {
//                                    DownRepeatService.CreateRepeatSchNextData2(maprepeat);
//
//                                    QueryAlarmData.writeAlarm(context);
//                                }
//                            }
//                        }
//                    }
                    if ("".equals(mMap.get(ScheduleTable.schRepeatDate))
                            || "0".equals(mMap.get(ScheduleTable.schRepeatLink))) {

                    } else {
                        if (map != null) {
                            String repdate = mMap
                                    .get(ScheduleTable.schRepeatDate);
                            String lastdate = StringUtils.getIsStringEqulesNull(map
                                    .get(CLRepeatTable.repDateOne));
                            String nextdate = StringUtils.getIsStringEqulesNull(map
                                    .get(CLRepeatTable.repDateTwo));
                            repeatSetChildEndUtils.setParentState(Integer.parseInt(mMap
                                    .get(ScheduleTable.schRepeatID)), repdate, nextdate, lastdate, map);
                        }
                    }
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, mMap.get(ScheduleTable.schID));
                    loadData(4, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();

                    Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras = new Bundle();
                    intentf.putExtras(extras);
                    getActivity().sendBroadcast(intentf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        month.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                    String date = inWeekUtils.AfterOneMonth(mMap.get(ScheduleTable.schDate));
                    App.getDBcApplication().updateScheduleDateData(id, date,
                            mMap.get(ScheduleTable.schTime));
                    App.getDBcApplication().updateSchReadData(
                            Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    App.getDBcApplication().updateSchRepeatLinkData(
                            Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    if (!"".equals(mMap.get(ScheduleTable.schRepeatDate))
                            || !"0".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                        if (map != null) {
                            String repdate = mMap
                                    .get(ScheduleTable.schRepeatDate);
                            String lastdate = StringUtils.getIsStringEqulesNull(map
                                    .get(CLRepeatTable.repDateOne));
                            String nextdate = StringUtils.getIsStringEqulesNull(map
                                    .get(CLRepeatTable.repDateTwo));
                            repeatSetChildEndUtils.setParentState(Integer.parseInt(mMap
                                    .get(ScheduleTable.schRepeatID)), repdate, nextdate, lastdate, map);
                        }
                    }
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                            ShareFile.SCHID, mMap.get(ScheduleTable.schID));
                    loadData(4, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();

                    Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras = new Bundle();
                    intentf.putExtras(extras);
                    getActivity().sendBroadcast(intentf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });


        zhuanfa.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

                Intent inten = new Intent(context, SelectionFirendActivity.class);
                inten.putExtra("schSourceType", "99");
                inten.putExtra("schRemark1", mMap.get(ScheduleTable.schRemark1));
                inten.putExtra("updateState", "1");
                inten.putExtra("schID", mMap.get(ScheduleTable.schID));
                inten.putExtra("titleid", mMap.get(ScheduleTable.schSourceDesc));
                inten.putExtra("titles", "");
                inten.putExtra("remark6", "");
                inten.putExtra("remark5", "");
                startActivity(inten);

                Intent LocalSyni = new Intent(context, LocalSynService.class);
                LocalSyni.setAction("LocalSynService");
                LocalSyni.putExtra("isMinLocal", true);
                LocalSyni.setPackage(context.getPackageName());
                context.startService(LocalSyni);
            }
        });


        //分类
        fenlei.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    CalenderFlagDialog calenderFlagDialog = new CalenderFlagDialog(context, R.style.dialog_translucent,
                            getActivity().getWindowManager(), mMap.get(ScheduleTable.schID), colorname, "");
                    calenderFlagDialog.setCallBack(new CalenderFlagDialog.CallBack() {
                        @Override
                        public void reminderEditTime(String name, String id) {
//                            loadData(true);
                            loadData(2, mMap.get(ScheduleTable.schID));
                        }
                    });
                    calenderFlagDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });


        /*****第二页****/
        final TextView copy_one = viewTwo.findViewById(R.id.copy_one);
        TextView delete = viewTwo.findViewById(R.id.delete);
        TextView shitinglings = viewTwo.findViewById(R.id.shitinglings);
        final TextView important = viewTwo.findViewById(R.id.important);

        if ("0".equals(mMap.get(ScheduleTable.schIsImportant))) {
//            important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_hui));
            important.setText("设为重要");
        } else {
//            important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_lv));
            important.setText("取消重要");
        }

        //重要
        important.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("0".equals(mMap.get(ScheduleTable.schIsImportant))) {
//                    important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_lv));
                    important.setText("取消重要");
                    mMap.put(ScheduleTable.schIsImportant, "1");
                    App.getDBcApplication().updatImportant(1, mMap.get(ScheduleTable.schID));
                } else {
//                    important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_hui));
                    important.setText("设为重要");
                    App.getDBcApplication().updatImportant(0, mMap.get(ScheduleTable.schID));
                    mMap.put(ScheduleTable.schIsImportant, "0");
                }
                try {
                    loadData(2, mMap.get(ScheduleTable.schID));
                    adapter.notifyDataSetChanged();
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();

            }
        });

//        Map<String, String> map1 = App.getDBcApplication().QueryhongFuData(mMap.get(ScheduleTable.schRepeatID));
//        if (map1 != null) {
//            if (!map1.get(CLRepeatTable.remark2).isEmpty()) {
//                WBA_FindFunctionMy.ListBean bean = App.getDBcApplication().get_tb_function_my(map1.get(CLRepeatTable.remark2));
//                if (bean != null && !bean.url.isEmpty()) {
//                    zhuanfa_ll.setVisibility(View.VISIBLE);
//                }
//            } else if (map1.get(CLRepeatTable.repContent).length() > 2 && map1.get(CLRepeatTable.repContent).substring(0,2).equals("#%")) {
//                List<CalenderNoteBean.PageBean.ItemsBean> list =
//                        App.getDBcApplication().getCalenderNoteDetailData(userid, map1.get(CLRepeatTable.repSourceDesc), false);
//                if (list.size() >= 1 && UriUtils.isUrl(list.get(0).contents)) {
//                    zhuanfa_ll.setVisibility(View.VISIBLE);
//                }
//            }
//        } else if(mMap.get(ScheduleTable.schRemark6) != null) {
//            WBA_FindFunctionMy.ListBean bean = App.getDBcApplication().get_tb_function_my(mMap.get(ScheduleTable.schRemark6));
//            if (bean != null && !bean.url.isEmpty()) {
//                zhuanfa_ll.setVisibility(View.VISIBLE);
//            } else if (mMap.get(ScheduleTable.schContent).length() > 2 && mMap.get(ScheduleTable.schContent).substring(0,2).equals("#%")) {
//                List<CalenderNoteBean.PageBean.ItemsBean> list =
//                        App.getDBcApplication().getCalenderNoteDetailData(userid, mMap.get(ScheduleTable.schSourceDesc), false);
//                if (list.size() >= 1 && UriUtils.isUrl(list.get(0).contents)) {
//                    zhuanfa_ll.setVisibility(View.VISIBLE);
//                }
//            }
//        }

        delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sharedPrefUtil.putString(context,
                        ShareFile.USERFILE,
                        ShareFile.DELETETYPE,
                        "1");
                try {
                    if (Integer.valueOf(mList.get(position).get(ScheduleTable.schcRecommendId)) > 0
                            && Integer.valueOf(mList.get(position).get(ScheduleTable.schAID)) == 0) {
                        if (!mList.get(position).get(ScheduleTable.schRepeatID).equals("0")) {
                            sharedPrefUtil.putString(context,
                                    ShareFile.USERFILE,
                                    ShareFile.UPLOADTYPE,
                                    "1");
                            deleteCalender(mMap, 0, position);
                        } else {
                            sharedPrefUtil.putString(context,
                                    ShareFile.USERFILE,
                                    ShareFile.UPLOADTYPE,
                                    "0");
                            alertDeleteDialog(mMap, 0, position);
                        }

                    } else {
                        sharedPrefUtil.putString(context,
                                ShareFile.USERFILE,
                                ShareFile.UPLOADTYPE,
                                "1");
                        deleteCalender(mMap, 0, position);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                Intent intentd = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                Bundle extrasd = new Bundle();
                intentd.putExtras(extrasd);
                getActivity().sendBroadcast(intentd);
                dialog.dismiss();
            }
        });


        try {
            fileDescriptor = getActivity().getAssets().openFd(
                    mMap.get(ScheduleTable.schRingCode)
                            + ".mp3");
            mediaPlayer.setDataSource(
                    fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            mediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        st_ll.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("0".equals(mMap.get(ScheduleTable.schIsImportant))) {
//                    important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_lv));
                    st_ll.setText("取消重要");
                    mMap.put(ScheduleTable.schIsImportant, "1");
                    App.getDBcApplication().updatImportant(1, mMap.get(ScheduleTable.schID));
                } else {
//                    important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_hui));
                    st_ll.setText("设为重要");
                    App.getDBcApplication().updatImportant(0, mMap.get(ScheduleTable.schID));
                    mMap.put(ScheduleTable.schIsImportant, "0");
                }
                try {
                    loadData(2, mMap.get(ScheduleTable.schID));
                    adapter.notifyDataSetChanged();
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        //试听铃声
        shitinglings.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    try {
                        AssetFileDescriptor fileDescriptor = getActivity()
                                .getAssets().openFd(
                                        mMap.get(ScheduleTable.schRingCode)
                                                + ".mp3");
                        mediaPlayer.setDataSource(
                                fileDescriptor.getFileDescriptor(),
                                fileDescriptor.getStartOffset(),
                                fileDescriptor.getLength());
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    mediaPlayer.start();
                }

            }
        });
        //复制文本
        copy_content.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(mMap.get(ScheduleTable.schContent));
            Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });
        copy_one.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(mMap.get(ScheduleTable.schContent));
            initRiliDiaLog(copy_one, mMap, true);
            dialog.dismiss();
        });
        final ImageView yd1 = more_pop_menu.findViewById(R.id.yd1);
        final ImageView yd2 = more_pop_menu.findViewById(R.id.yd2);

        viewList.add(viewOne);

        if (!mMap.get(ScheduleTable.schSourceType).equals("3")
                && !mMap.get(ScheduleTable.schSourceType).equals("4")
                && !mMap.get(ScheduleTable.schSourceType).equals("5")) {
            viewList.add(viewTwo);
        } else {
            yd1.setVisibility(View.GONE);
            yd2.setVisibility(View.GONE);
        }

        ViewAdapter viewAdapter = new ViewAdapter(viewList);
        myViewPager.setAdapter(viewAdapter);


        myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (!mMap.get(ScheduleTable.schSourceType).equals("3")
                        && !mMap.get(ScheduleTable.schSourceType).equals("4")
                        && !mMap.get(ScheduleTable.schSourceType).equals("5")) {
                    yd1.setBackground(getResources().getDrawable(R.drawable.calender_new_detail_yd1));
                    yd2.setBackground(getResources().getDrawable(R.drawable.calender_new_detail_yd1));
                    if (position == 0) {
                        yd1.setBackground(getResources().getDrawable(R.drawable.calender_new_detail_yd2));
                    }
                    if (position == 1) {
                        yd2.setBackground(getResources().getDrawable(R.drawable.calender_new_detail_yd2));
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void dialogMorningTimeOnClick(TextView time_tv, Map<String, String> mMap) {
        final BaseDialog dialog = new BaseDialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
//        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_gundong_time, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();
        dialog.setCallBack(new BaseDialog.CallBack() {
            @Override
            public void onTouchOutside() {
                sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.CLOCKORDER, "0");
                dialog.dismiss();
            }
        });
        new TimeOnClick(dialog, more_pop_menu, time_tv, mMap);
    }

    class TimeOnClick {

        private View view;
        private Dialog dialog;
        // private PickerView hour_pv;
        // private PickerView minute_pv;
        CycleWheelView hour_cy;
        CycleWheelView min_cy;
        String hour;
        String minute;
        private String timeSet = "";
        private TextView time_tv;

        Map<String, String> mMap;
        ToggleButton toggleButton;

        @SuppressLint("NewApi")
        public TimeOnClick(Dialog dialog, View view, TextView time_tv, Map<String, String> mMap) {
            this.dialog = dialog;
            this.view = view;
            this.time_tv = time_tv;
            this.mMap = mMap;
            timeSet = mMap.get(ScheduleTable.schTime);
            initview();
            initdata();
        }

        private void initview() {
            hour_cy = (CycleWheelView) view.findViewById(R.id.hour_cy);
            min_cy = (CycleWheelView) view.findViewById(R.id.min_cy);
//            view.findViewById(R.id.bp).setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dialog.dismiss();
//                    initDiaLog(time_tv, mMap);
//                }
//            });

            toggleButton = (ToggleButton) view.findViewById(R.id.toggle);
            if (mMap.get(ScheduleTable.schDisplayTime).equals("0")) {
                toggleButton.setChecked(true);
            } else {
                toggleButton.setChecked(false);
            }
            toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                             boolean isChecked) {
                    if (isChecked) {
                        // 选中
                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                        App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), mMap.get(ScheduleTable.schTime), 0);


                        if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                            App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                        }
                        loadData(2, mMap.get(ScheduleTable.schID));
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        getActivity().sendBroadcast(intentappwidget);
                    } else {
                        // 未选中
                        int schID1 = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                                ShareFile.SCHID, schID1 + "");
                        App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), timeSet, 1);

                        if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                            App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                        }
                        loadData(2, mMap.get(ScheduleTable.schID));
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());

                        Intent intentappwidget1 = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras1 = new Bundle();
                        intentappwidget1.putExtras(extras1);
                        getActivity().sendBroadcast(intentappwidget1);
                    }
                }
            });
        }

        private void initdata() {
            int curHours = Integer.parseInt(timeSet.split(":")[0]);
            int curMinutes = Integer.parseInt(timeSet.split(":")[1]);
            hour = curHours + "";
            minute = curMinutes + "";
            int currentHoursIndex = 0;
            int currentMinutesIndex = 0;
            List<String> hours = new ArrayList<String>();
            List<String> minutes = new ArrayList<String>();
            for (int i = 0; i < 24; i++) {
                hours.add(i < 10 ? "0" + i : "" + i);

            }
            for (int i = 0; i < 60; i++) {
                minutes.add(i < 10 ? "0" + i : "" + i);
            }
            for (int i = 0; i < hours.size(); i++) {
                if (curHours == Integer.parseInt(hours.get(i))) {
                    currentHoursIndex = i;
                }
            }
            for (int i = 0; i < minutes.size(); i++) {
                if (curMinutes == Integer.parseInt(minutes.get(i))) {
                    currentMinutesIndex = i;
                }
            }
            hour_cy.setLabels(hours);
            try {
                hour_cy.setWheelSize(5);
            } catch (CycleWheelView.CycleWheelViewException e) {
                e.printStackTrace();
            }
            hour_cy.setCycleEnable(true);
            hour_cy.setSelection(currentHoursIndex);
            hour_cy.setAlphaGradual(0.6f);
            hour_cy.setDivider(getResources().getColor(R.color.gongkai_txt), 1);
            hour_cy.setSolid(Color.WHITE, Color.WHITE);
            hour_cy.setLabelColor(getResources().getColor(R.color.gongkai_txt));
            hour_cy.setLabelSelectColor(Color.BLACK);
            hour_cy.setOnWheelItemSelectedListener(new CycleWheelView.WheelItemSelectedListener() {
                @Override
                public void onItemSelected(int position, String label) {
                    hour = Integer.parseInt(label) < 10 ? "0"
                            + Integer.parseInt(label) : label;
                    minute = Integer.parseInt(minute) < 10 ? "0"
                            + Integer.parseInt(minute) : minute;

                    int schID1 = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID1 + "");
                    if (!timeSet.equals(hour + ":" + minute)) {
                        toggleButton.setChecked(false);
                    }
                    timeSet = hour + ":" + minute;
                    App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), timeSet, toggleButton.isChecked() ? 0 : 1);

                    if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                        App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                    }
                    loadData(2, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());

                    Intent intentappwidget1 = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras1 = new Bundle();
                    intentappwidget1.putExtras(extras1);
                    getActivity().sendBroadcast(intentappwidget1);
                }
            });

            min_cy.setLabels(minutes);
            try {
                min_cy.setWheelSize(5);
            } catch (CycleWheelView.CycleWheelViewException e) {
                e.printStackTrace();
            }
            min_cy.setCycleEnable(true);
            min_cy.setSelection(currentMinutesIndex);
            min_cy.setAlphaGradual(0.6f);
            min_cy.setDivider(getResources().getColor(R.color.gongkai_txt), 1);
            min_cy.setSolid(Color.WHITE, Color.WHITE);
            min_cy.setLabelColor(getResources().getColor(R.color.gongkai_txt));
            min_cy.setLabelSelectColor(Color.BLACK);
            min_cy.setOnWheelItemSelectedListener(new CycleWheelView.WheelItemSelectedListener() {
                @Override
                public void onItemSelected(int position, String label) {
                    hour = Integer.parseInt(hour) < 10 ? "0"
                            + Integer.parseInt(hour) : hour;
                    minute = Integer.parseInt(label) < 10 ? "0"
                            + Integer.parseInt(label) : label;
                    int schID1 = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID1 + "");
                    if (!timeSet.equals(hour + ":" + minute)) {
                        toggleButton.setChecked(false);
                    }
                    timeSet = hour + ":" + minute;
                    App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), timeSet, toggleButton.isChecked() ? 0 : 1);

                    if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                        App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                    }
                    loadData(2, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());

                    Intent intentappwidget1 = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras1 = new Bundle();
                    intentappwidget1.putExtras(extras1);
                    getActivity().sendBroadcast(intentappwidget1);
                }
            });
        }
    }

    String beforeType = "";

    private void initDiaLog(TextView time_tv, Map<String, String> mMap) {
        final BaseDialog dialog = new BaseDialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
//        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_calender_time, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();
        dialog.setCallBack(new BaseDialog.CallBack() {
            @Override
            public void onTouchOutside() {
                sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                        ShareFile.CLOCKORDER, "1");
                dialog.dismiss();
            }
        });

        new MyClick(dialog, more_pop_menu, time_tv, mMap);
    }

    class MyClick implements OnClickListener {

        private Dialog dialog;
        private RelativeLayout rela_hour;
        private RelativeLayout rela_minutes;
        private int hours = 12;
        private int minutes = 0;
        private int width;
        private int centerX;
        private int centerY;
        private Calendar calendar;
        private int lastMinutes;
        private TextView dialog_tv_state, dialog_tv_state1;
        private int grState;// 结果为0是上午 结果为1是下午
        private String chooseHour;
        private String chooseMinute;

        private TextView tv_clock_state;
        private LinearLayout ll_clock, state_ll;
        private TextView tv_clock_time;
        private TextView tv_clock_beforetime;
        private TextView time_tv, tv_gt;

        private RelativeLayout date_re;
        Map<String, String> mMap;
        String time;

        private MyClick(Dialog dialog, View more_pop_menu, TextView time_tvs, Map<String, String> mMap) {
            this.dialog = dialog;
            this.time_tv = time_tvs;
            this.mMap = mMap;
            time = mMap.get(ScheduleTable.schTime);
            calendar = Calendar.getInstance();
            // if (isNeedPush) {
            String[] times;

            if ("全天".equals(time)) {
                times = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                        ShareFile.ALLTIME, "08:58").split(":");
            } else {
                times = time.split(":");
            }
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(times[1]));
            // }
            rela_hour = (RelativeLayout) more_pop_menu
                    .findViewById(R.id.rela_hour);
            rela_minutes = (RelativeLayout) more_pop_menu
                    .findViewById(R.id.rela_minutes);

            dialog_tv_state = (TextView) more_pop_menu
                    .findViewById(R.id.dialog_tv_state);
            date_re = (RelativeLayout) more_pop_menu
                    .findViewById(R.id.date_re);
            dialog_tv_state1 = (TextView) more_pop_menu
                    .findViewById(R.id.dialog_tv_state1);
            state_ll = (LinearLayout) more_pop_menu
                    .findViewById(R.id.state_ll);
            state_ll.setOnClickListener(this);
            tv_clock_state = (TextView) more_pop_menu
                    .findViewById(R.id.tv_clock_state);
            tv_clock_state.setOnClickListener(this);

            tv_gt = (TextView) more_pop_menu.findViewById(R.id.tv_gt);
            tv_gt.setOnClickListener(this);
            ll_clock = (LinearLayout) more_pop_menu.findViewById(R.id.ll_clock);
            ll_clock.setOnClickListener(this);

            tv_clock_time = (TextView) more_pop_menu.findViewById(R.id.tv_clock_time);
            tv_clock_beforetime = (TextView) more_pop_menu.findViewById(R.id.tv_clock_beforetime);

            width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
            int haf = Utils.dipTopx(context, 20);
            centerX = width / 2 - Utils.dipTopx(context, 16);
            centerY = width / 2 - Utils.dipTopx(context, 16) - haf;

            initclockValue();
            initHour();
            initMinutes();

            grState = calendar.get(Calendar.AM_PM);
            if (grState == 1) {// 上午
                dialog_tv_state1.setTextColor(Color.parseColor("#08f0ff"));
                dialog_tv_state1.setTextSize(30);
                dialog_tv_state.setTextColor(Color.parseColor("#aaaaaa"));
                dialog_tv_state.setTextSize(14);
                grState = 1;
                calendar.set(Calendar.AM_PM, grState);
            } else if (grState == 0) {// 下午
                dialog_tv_state.setTextColor(Color.parseColor("#08f0ff"));
                dialog_tv_state.setTextSize(30);
                dialog_tv_state1.setTextColor(Color.parseColor("#aaaaaa"));
                dialog_tv_state1.setTextSize(14);
                grState = 0;
                calendar.set(Calendar.AM_PM, grState);
            }
        }

        private void initclockValue() {
            tv_clock_time.setText(time);
            if (time.split(":")[0].substring(0, 1).equals("0")) {
                if (Integer.valueOf(time.split(":")[0].substring(1, time.split(":")[0].length())) >= 0 &&
                        Integer.valueOf(time.split(":")[0].substring(1, time.split(":")[0].length())) <= 6) {
                    tv_clock_time.setText("凌晨 " + time);
                }
            }
        }

        private void initHour() {
            int hour = calendar.get(Calendar.HOUR);
            if (hour == 0) {
                hour = 12;
            }
            int hourRadius = Utils.dipTopx(context, 90); // 设置圆半径
            for (int i = 12; i >= 1; i--) {
                int dy = (int) (hourRadius * Math.cos((Math.PI / 6.0) * i));
                int dx = (int) (hourRadius * Math.sin((Math.PI / 6.0) * i));

                int x1 = centerX + dx;
                int y1 = centerY - dy;

                String text = hours < 10 ? "0" + hours : "" + hours;

                TextView textView = new TextView(context);
                textView.setText(text);
                textView.setTextColor(Color.WHITE);
                textView.setTextSize(18.0f);
                textView.setGravity(Gravity.CENTER);
                textView.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                textView.setTag(i);
                textView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        chooseHour = v.getTag().toString();
                        chageHour(Integer.parseInt(chooseHour));
                        calendar.set(Calendar.HOUR,
                                Integer.parseInt(chooseHour));
                        calendar.set(Calendar.MINUTE,
                                Integer.parseInt(chooseMinute));
                        if (grState == 0) {// 上午
                            calendar.set(Calendar.AM_PM, 0);
                        } else if (grState == 1) {// 下午
                            calendar.set(Calendar.AM_PM, 1);
                        }
                        String calendarHour = calendar
                                .get(Calendar.HOUR_OF_DAY) < 10 ? "0"
                                + calendar.get(Calendar.HOUR_OF_DAY) : ""
                                + calendar.get(Calendar.HOUR_OF_DAY);
                        String calendarMinute = calendar.get(Calendar.MINUTE) < 10 ? "0"
                                + calendar.get(Calendar.MINUTE)
                                : "" + calendar.get(Calendar.MINUTE);
                        time_tv.setText("\"" + calendarHour + ":" + calendarMinute + "\"\n设置时间");
                        tv_clock_time.setText(((0 <= calendar
                                .get(Calendar.HOUR_OF_DAY) && calendar
                                .get(Calendar.HOUR_OF_DAY) <= 6) ? "凌晨" : "") + calendarHour + ":" + calendarMinute);

                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                                ShareFile.SCHID, schID + "");
                        App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), calendarHour + ":" + calendarMinute, 1);

                        if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                            App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                        }

                        loadData(2, mMap.get(ScheduleTable.schID));
//                        updataList();
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                        UpLoadData();

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        getActivity().sendBroadcast(intentappwidget);

                    }
                });

                if (hour == i) {
                    if (time.equals("全天")) {
                        textView.setBackgroundDrawable(null);
                    } else {
                        chooseHour = text;
                        textView.setTextColor(Color.WHITE);
                        textView.setBackgroundResource(R.mipmap.icon_shuzi1);
                    }
                } else {
                    textView.setBackgroundDrawable(null);
                }

                rela_hour.addView(textView);

                textView.setAnimation(animTranslate(centerX, centerY, x1, y1, textView, 200));

                hours--;
            }
        }

        private void initMinutes() {
            int minute = calendar.get(Calendar.MINUTE);
            int result = minute % 5;
            if (result != 0) {
                int division = minute / 5;
                minute = division * 5;
            }
            int minutesRadius = Utils.dipTopx(context, 140); // 设置圆半径
            for (int i = 0; i < 12; i++) {
                int dy = (int) (minutesRadius * Math.cos((Math.PI / 6.0) * i));
                int dx = (int) (minutesRadius * Math.sin((Math.PI / 6.0) * i));

                int x1 = centerX + dx;
                int y1 = centerY - dy;

                String text = minutes * 5 < 10 ? "0" + minutes * 5 : "" + minutes * 5;

                TextView textView = new TextView(context);
                textView.setText(text);
                textView.setTextColor(Color.WHITE);
                textView.setTextSize(18.0f);
                textView.setGravity(Gravity.CENTER);
                textView.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                textView.setTag(text);
                textView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        chooseMinute = v.getTag().toString();
                        chageMinutes(Integer.parseInt(chooseMinute) / 5);
                        lastMinutes = Integer.parseInt(chooseMinute) / 5;
                        calendar.set(Calendar.HOUR,
                                Integer.parseInt(chooseHour));
                        calendar.set(Calendar.MINUTE,
                                Integer.parseInt(chooseMinute));
                        if (grState == 0) {// 上午
                            calendar.set(Calendar.AM_PM, 0);
                        } else if (grState == 1) {// 下午
                            calendar.set(Calendar.AM_PM, 1);
                        }
                        String calendarHour = calendar
                                .get(Calendar.HOUR_OF_DAY) < 10 ? "0"
                                + calendar.get(Calendar.HOUR_OF_DAY) : ""
                                + calendar.get(Calendar.HOUR_OF_DAY);
                        String calendarMinute = calendar.get(Calendar.MINUTE) < 10 ? "0"
                                + calendar.get(Calendar.MINUTE)
                                : "" + calendar.get(Calendar.MINUTE);
                        time_tv.setText("\"" + calendarHour + ":" + calendarMinute + "\"\n设置时间");
                        tv_clock_time.setText(((0 <= calendar
                                .get(Calendar.HOUR_OF_DAY) && calendar
                                .get(Calendar.HOUR_OF_DAY) <= 6) ? "凌晨" : "") + calendarHour + ":" + calendarMinute);

                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                                ShareFile.SCHID, schID + "");

                        App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), calendarHour + ":" + calendarMinute, 1);
                        if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                            App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                        }
                        loadData(2, mMap.get(ScheduleTable.schID));
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                        UpLoadData();

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        getActivity().sendBroadcast(intentappwidget);
                    }
                });
                if (minute == Integer.parseInt(text)) {
                    if (time.equals("全天")) {
                        textView.setBackgroundDrawable(null);
                    } else {
                        lastMinutes = i;
                        chooseMinute = text;
                        textView.setTextColor(Color.WHITE);
                        textView.setBackgroundResource(R.mipmap.icon_shuzi2);
                    }
                } else {
                    textView.setBackgroundDrawable(null);
                }
                rela_minutes.addView(textView);
                textView.setAnimation(animTranslate(centerX, centerY, x1, y1, textView, 200));

                minutes++;
            }
        }

        private void chageHour(int hours) {
            for (int i = rela_hour.getChildCount() - 1; i >= 0; i--) {
                TextView tv_hour = (TextView) rela_hour.getChildAt(i);
                if (hours == Integer.parseInt(tv_hour.getTag().toString())) {
                    tv_hour.setBackgroundResource(R.mipmap.icon_shuzi1);
                } else {
                    tv_hour.setBackgroundDrawable(null);
                }
            }
        }

        private void chageMinutes(int minutes) {
            TextView textView = (TextView) rela_minutes.getChildAt(lastMinutes);
            textView.setBackgroundDrawable(null);
            TextView tv_minutes = (TextView) rela_minutes.getChildAt(minutes);
            tv_minutes.setBackgroundResource(R.mipmap.icon_shuzi2);
        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_gt:
                    dialogMorningTimeOnClick(time_tv, mMap);
                    dialog.dismiss();
                    break;
                case R.id.state_ll:
                    calendar.set(Calendar.HOUR, Integer.parseInt(chooseHour));
                    calendar.set(Calendar.MINUTE, Integer.parseInt(chooseMinute));
                    if (grState == 0) {// 上午
                        dialog_tv_state1.setTextColor(Color.parseColor("#08f0ff"));
                        dialog_tv_state1.setTextSize(30);
                        dialog_tv_state.setTextColor(Color.parseColor("#aaaaaa"));
                        dialog_tv_state.setTextSize(14);
                        grState = 1;
                        calendar.set(Calendar.AM_PM, grState);
                    } else if (grState == 1) {// 下午
                        dialog_tv_state.setTextColor(Color.parseColor("#08f0ff"));
                        dialog_tv_state.setTextSize(30);
                        dialog_tv_state1.setTextColor(Color.parseColor("#aaaaaa"));
                        dialog_tv_state1.setTextSize(14);
                        grState = 0;
                        calendar.set(Calendar.AM_PM, grState);
                    }
                    String calendarHour = calendar.get(Calendar.HOUR_OF_DAY) < 10 ? "0"
                            + calendar.get(Calendar.HOUR_OF_DAY)
                            : "" + calendar.get(Calendar.HOUR_OF_DAY);
                    String calendarMinute = calendar.get(Calendar.MINUTE) < 10 ? "0"
                            + calendar.get(Calendar.MINUTE)
                            : "" + calendar.get(Calendar.MINUTE);
                    time_tv.setText("\"" + calendarHour + ":" + calendarMinute + "\"\n设置时间");
                    tv_clock_time.setText(((0 <= calendar
                            .get(Calendar.HOUR_OF_DAY) && calendar
                            .get(Calendar.HOUR_OF_DAY) <= 6) ? "凌晨" : "") + calendarHour + ":" + calendarMinute);

                    int schID1 = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                            ShareFile.SCHID, schID1 + "");
                    App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), calendarHour + ":" + calendarMinute, 1);

                    if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                        App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                    }
                    loadData(2, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity()
                            .getApplicationContext());
                    UpLoadData();

                    Intent intentappwidget1 = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras1 = new Bundle();
                    intentappwidget1.putExtras(extras1);
                    getActivity().sendBroadcast(intentappwidget1);
                    break;

                case R.id.tv_clock_state:
                    time_tv.setText("\"全天\"\n设置时间");
                    int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                            ShareFile.SCHID, schID + "");
                    App.getDBcApplication().updateSceduleDataTime(mMap.get(ScheduleTable.schID), mMap.get(ScheduleTable.schTime), 0);


                    if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                        App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                    }
                    loadData(2, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity()
                            .getApplicationContext());
                    UpLoadData();

                    Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras = new Bundle();
                    intentappwidget.putExtras(extras);
                    getActivity().sendBroadcast(intentappwidget);
                    break;
                default:
                    dialog.dismiss();

                    break;
            }
        }

    }

    private Animation animationTranslate;
    private RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(0, 0);

    // 移动的动画效果
    /*
     * TranslateAnimation(float fromXDelta, float toXDelta, float
     * fromYDelta,float toYDelta)
     *
     * float fromXDelta:这个参数表示动画开始的点离当前View X坐标上的差值；
     *
     * float toXDelta, 这个参数表示动画结束的点离当前View X坐标上的差值；
     *
     * float fromYDelta, 这个参数表示动画开始的点离当前View Y坐标上的差值；
     *
     * float toYDelta)这个参数表示动画开始的点离当前View Y坐标上的差值；
     */
    protected Animation animTranslate(float toX, float toY, final int x1,
                                      final int y1, final TextView textView, long durationMillis) {
        animationTranslate = new TranslateAnimation(toX, toX, toY, toY);
        animationTranslate.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                params = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(x1, y1, 0, 0);
                textView.setLayoutParams(params);
                textView.setPadding(12, 7, 12, 7);
                textView.clearAnimation();
            }
        });
        animationTranslate.setDuration(durationMillis);
        return animationTranslate;
    }

    private void initValues(int setBefore) {
        if (setBefore == 0) {
            indexti = 0;
        } else if (setBefore == 5) {
            indexti = 1;
        } else if (setBefore == 15) {
            indexti = 2;
        } else if (setBefore == 30) {
            indexti = 3;
        } else if (setBefore == 60) {
            indexti = 4;
        } else if (setBefore == 120) {
            indexti = 5;
        } else if (setBefore == 24 * 60) {
            indexti = 6;
        } else if (setBefore == 48 * 60) {
            indexti = 7;
        } else if (setBefore == 7 * 24 * 60) {
            indexti = 8;
        }
    }


    /******日历*****/
    int[] solartime = new int[25];
    boolean isLeap = false;
    boolean isRed = false;
    ArrayList<HashMap<String, String>> data;
    String today;
    int temp_day;
    int temp_month;
    int temp_year;

    int to_day;
    int to_month;
    int to_year;
    int standard_day;
    int standard_month;
    String ToMonth = "01";
    int standard_year;
    String holiday = "";
    String curDate = "";

    int sourse;//
    String dateTime = "";// 日期
    private TextView title;

    MyLinearLayout dataLinear;
    Handler handlerrili;
    LinearLayout.LayoutParams mLayoutParamss = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);

    /**
     * 加载数据
     */
    private void loadDatarili() {
        GenData(true, curDate);
        GenView();
    }

    @SuppressLint("HandlerLeak")
    private void initRiliDiaLog(final TextView date_tv, final Map<String, String> mMap, final boolean isCopyCalender) {
        final Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_calender_rili, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();
        if (mMap == null) {
            ToMonth = DateUtil.formatDateMMDD(new Date());
            Today = DateUtil.formatDateMMDD(new Date());
        } else {
            ToMonth = mMap.get(ScheduleTable.schDate).substring(5, 7);
            Today = mMap.get(ScheduleTable.schDate).substring(8, mMap.get(ScheduleTable.schDate).length());//2017-01-01
        }

        today_tv = (TextView) more_pop_menu.findViewById(R.id.today);
        dataLinear = (MyLinearLayout) more_pop_menu.findViewById(R.id.datalinear);
        title = (TextView) more_pop_menu.findViewById(R.id.title);
        dataLinear.setBackgroundColor(Color.WHITE);
        today_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                curDate = DateUtil.formatDate(new Date());// new Date()为获取当前系统时间
                loadDatarili();
            }
        });
        more_pop_menu.findViewById(R.id.lastmonth).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (standard_month == 1) {
                    standard_month = 12;
                    standard_year--;
                } else {
                    standard_month--;
                }
                GenData(false, curDate);
                GenView();
                title.setText(standard_year + "年" + standard_month + "月");
                dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.right_in));

            }
        });
        more_pop_menu.findViewById(R.id.nextmonth).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (standard_month == 12) {
                    standard_month = 1;
                    standard_year++;
                } else {
                    standard_month++;
                }
                GenData(false, curDate);
                GenView();
                title.setText(standard_year + "年" + standard_month + "月");
                dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.left_in));

            }
        });
        handlerrili = new Handler() {
            public void handleMessage(Message msg) {
                if (msg == null) {
                    return;
                }
                switch (msg.what) {
                    case 0:
                        if (standard_month == 1) {
                            standard_month = 12;
                            standard_year--;
                        } else {
                            standard_month--;
                        }
                        GenData(false, curDate);
                        GenView();
                        title.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.right_in));
                        break;

                    case 1:
                        if (standard_month == 12) {
                            standard_month = 1;
                            standard_year++;
                        } else {
                            standard_month++;
                        }
                        GenData(false, curDate);
                        GenView();
                        title.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.left_in));
                        break;

                    case 2:
                        standard_year--;
                        GenData(false, curDate);
                        GenView();
                        title.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.down_in));
                        break;

                    case 3:
                        standard_year++;
                        GenData(false, curDate);
                        GenView();
                        title.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.up_in));
                        break;

                    case 9:
                        if (mMap == null) {
                            dialogDaoqili(msg.obj + "");
                        } else {
                            if (isCopyCalender) {
                                int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                                App.getDBcApplication().copyCalnederNoteData(userid,
                                        mMap.get(ScheduleTable.schID),
                                        mMap.get(ScheduleTable.schSourceDesc),
                                        (msg.obj + "").split("\n")[0].replace("\"", ""));
                                Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show();
                                loadData(0, schID + "");
                                UpLoadData();
                            } else {
                                date_tv.setText(msg.obj + "");
                                int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                                sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                                App.getDBcApplication().updateSceduleDataDate(mMap.get(ScheduleTable.schID), (msg.obj + "").split("\n")[0].replace("\"", ""));
                                if (!mMap.get(ScheduleTable.schRepeatID).equals("0")) {
                                    App.getDBcApplication().updateSchuledRepeatTo(mMap.get(ScheduleTable.schID));
                                }
                                if (DateUtil.parseDate((msg.obj + "").split("\n")[0].replace("\"", "")).before(DateUtil.parseDate(DateUtil.formatDate(new Date())))) {
                                    if (mMap.get(ScheduleTable.schDisplayTime).equals("1") && mMap.get(ScheduleTable.schIsPostpone).equals("0")) {
                                        loadData(1, mMap.get(ScheduleTable.schID));
                                    }
                                } else {
                                    loadData(2, mMap.get(ScheduleTable.schID));
                                }
                                UpLoadData();
                            }
                            QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                            Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                            Bundle extras = new Bundle();
                            intentappwidget.putExtras(extras);
                            getActivity().sendBroadcast(intentappwidget);

                        }

                        dialog.dismiss();


                        break;

                    case 11:
                        Toast.makeText(context, "网络中断", Toast.LENGTH_LONG).show();
                        break;

                    case 12:
                        Toast.makeText(context, "服务器错误", Toast.LENGTH_LONG).show();
                        break;
                }
            }
        };
        dataLinear.setHandler(handlerrili);


        new LoadDataAsyncTask().execute();


    }

    class LoadDataAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
//			dialog.dismiss();
            GenData(true, curDate);
            GenView();
        }

    }

    public ArrayList<HashMap<String, String>> GenData(boolean isfirst, String date) {
        if (!date.equals("") && isfirst) {
            data = new ArrayList<HashMap<String, String>>();
            to_year = Integer.parseInt(date.split("-")[0].toString());
            to_month = Integer.parseInt(date.split("-")[1].toString());
            to_day = Integer.parseInt(date.split("-")[2].toString());
            temp_day = to_day;
            temp_month = to_month;
            temp_year = to_year;
            standard_day = to_day;
            standard_month = to_month;
            standard_year = to_year;
            today = date;
            title.setText(standard_year + "年" + standard_month + "月");
        } else {
            if (isfirst) {
                data = new ArrayList<HashMap<String, String>>();
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(System.currentTimeMillis());
                to_year = c.get(Calendar.YEAR);
                to_month = c.get(Calendar.MONTH);
                to_day = c.get(Calendar.DAY_OF_MONTH);

                to_month++;
                temp_day = to_day;
                temp_month = to_month;
                temp_year = to_year;
                standard_day = to_day;
                standard_month = to_month;
                standard_year = to_year;

                today = to_year + "-"
                        + (to_month > 9 ? "" + to_month : "0" + to_month) + "-"
                        + (to_day > 9 ? "" + to_day : "0" + to_day);
                title.setText(standard_year + "年" + standard_month + "月");
            } else {
                data = new ArrayList<HashMap<String, String>>();
                temp_day = standard_day;
                temp_month = standard_month;
                temp_year = standard_year;

            }
        }
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("day", temp_day + "");

        map.put("isMonth", "1"); // 1是本月
        String tempStrT = temp_year + "-"
                + (temp_month > 9 ? "" + temp_month : "0" + temp_month) + "-"
                + (temp_day > 9 ? "" + temp_day : "0" + temp_day);
        if ("".equals(StringUtils.getIsStringEqulesNull(tempStrT))) {
            tempStrT = today;
        }
        if (today.equals(tempStrT)) {
            map.put("isToday", "1"); // 1是今天
            map.put("time", today);
        } else {
            map.put("isToday", "0"); // 1是今天
            map.put("time", tempStrT);
        }
        try {
            if (CalHoliday(Integer.valueOf(temp_month
                    + (temp_day > 9 ? "" + temp_day : "0" + temp_day)))) {
                map.put("lunar", holiday);
            } else {
                map.put("lunar", CalendarChange.CalendarChange(tempStrT));
            }
            if (isRed) {
                map.put("isHoliday", "1"); // 1节日
                isRed = false;
            } else {
                map.put("isHoliday", "0"); // 1节日
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        data.add(map);
        for (int i = temp_day - 1; i > 0; i--) {
            String tempStr = temp_year + "-"
                    + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                    + "-" + (i > 9 ? "" + i : "0" + i);
            map = new HashMap<String, String>();
            map.put("day", i + "");
            map.put("time", tempStr);
            map.put("isToday", "0"); // 1是今天
            map.put("isMonth", "1"); // 1是本月
            try {
                if (CalHoliday(Integer.valueOf("" + temp_month
                        + (i > 9 ? "" + i : "0" + i)))) {
                    map.put("lunar", holiday);
                } else {
                    map.put("lunar", CalendarChange.CalendarChange(tempStr));
                }
                if (isRed) {
                    map.put("isHoliday", "1"); // 1节日
                    isRed = false;
                } else {
                    map.put("isHoliday", "0"); // 1节日
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.add(0, map);
        }
        int te_week = calWeek(temp_year, temp_month, 1);
        if (temp_month == 1) {
            temp_year--;
            temp_month = 12;
        } else {
            temp_month--;
        }
        calLeapYear(temp_year);
        if (temp_month == 4 || temp_month == 6 || temp_month == 9
                || temp_month == 11) {
            for (int i = 30; i > 30 - te_week; i--) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 是今天
                map.put("isMonth", "0"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(0, map);
            }
        } else if (temp_month == 2) {
            if (isLeap) {
                for (int i = 29; i > 29 - te_week; i--) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + i);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 1是今天
                    map.put("isMonth", "0"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(0, map);
                }
            } else {
                for (int i = 28; i > 28 - te_week; i--) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + i);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 1是今天
                    map.put("isMonth", "0"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(0, map);
                }
            }
        } else {
            for (int i = 31; i > 31 - te_week; i--) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 1是今天
                map.put("isMonth", "0"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(0, map);
            }
        }
        if (temp_month == 12) {
            temp_year++;
            temp_month = 1;
        } else {
            temp_month = temp_month + 1;
        }
        calLeapYear(temp_year);
        if (temp_month == 4 || temp_month == 6 || temp_month == 9
                || temp_month == 11) {
            for (int i = to_day + 1; i <= 30; i++) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 1是今天
                map.put("isMonth", "1"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(map);
            }
        } else if (temp_month == 2) {
            if (isLeap) {
                for (int i = to_day + 1; i <= 29; i++) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + i);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 是今天
                    map.put("isMonth", "1"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(map);
                }
            } else {
                for (int i = to_day + 1; i <= 28; i++) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + to_day);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 是今天
                    map.put("isMonth", "1"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(map);
                }
            }
        } else {
            for (int i = to_day + 1; i <= 31; i++) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 是今天
                map.put("isMonth", "1"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(map);
            }
        }
        if (temp_month >= 12) {
            temp_year++;
            temp_month = 1;
        } else {
            temp_month++;
        }
        int mm = data.size();
        for (int i = 1; i <= 42 - mm; i++) {
            String tempStr = temp_year + "-"
                    + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                    + "-" + (i > 9 ? "" + i : "0" + i);
            map = new HashMap<String, String>();
            map.put("day", i + "");
            map.put("time", tempStr);
            map.put("isToday", "0"); // 是今天
            map.put("isMonth", "0"); // 1是本月
            try {
                if (CalHoliday(Integer.valueOf("" + temp_month
                        + (i > 9 ? "" + i : "0" + i)))) {
                    map.put("lunar", holiday);
                } else {
                    map.put("lunar", CalendarChange.CalendarChange(tempStr));
                }
                if (isRed) {
                    map.put("isHoliday", "1"); // 1节日
                    isRed = false;
                } else {
                    map.put("isHoliday", "0"); // 1节日
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.add(map);
        }
        return data;
    }

    public boolean CalHoliday(int t) {
        boolean is = false;
        switch (t / 100) {
            case 2:
                if (t == solartime[0]) {
                    holiday = "立春";
                    is = true;
                } else if (t == solartime[1]) {
                    holiday = "雨水";
                    is = true;
                }
                break;
            case 3:
                if (t == solartime[2]) {
                    holiday = "惊蛰";
                    is = true;
                } else if (t == solartime[3]) {
                    holiday = "春分";
                    is = true;
                }
                break;
            case 4:
                if (t == solartime[4]) {
                    holiday = "清明";
                    is = true;
                } else if (t == solartime[5]) {
                    holiday = "谷雨";
                    is = true;
                }
                break;
            case 5:
                if (t == solartime[6]) {
                    holiday = "立夏";
                    is = true;
                } else if (t == solartime[7]) {
                    holiday = "小满";
                    is = true;
                }
                break;
            case 6:
                if (t == solartime[8]) {
                    holiday = "芒种";
                    is = true;
                } else if (t == solartime[9]) {
                    holiday = "夏至";
                    is = true;
                }
                break;
            case 7:
                if (t == solartime[10]) {
                    holiday = "小暑";
                    is = true;
                } else if (t == solartime[11]) {
                    holiday = "大暑";
                    is = true;
                }
                break;
            case 8:
                if (t == solartime[12]) {
                    holiday = "立秋";
                    is = true;
                } else if (t == solartime[13]) {
                    holiday = "处暑";
                    is = true;
                }
                break;
            case 9:
                if (t == solartime[14]) {
                    holiday = "白露";
                    is = true;
                } else if (t == solartime[15]) {
                    holiday = "秋分";
                    is = true;
                }
                break;
            case 10:
                if (t == solartime[16]) {
                    holiday = "寒露";
                    is = true;
                } else if (t == solartime[17]) {
                    holiday = "霜降";
                    is = true;
                }
                break;
            case 11:
                if (t == solartime[18]) {
                    holiday = "立冬";
                    is = true;
                } else if (t == solartime[19]) {
                    holiday = "小雪";
                    is = true;
                }
                break;
            case 12:
                if (t == solartime[20]) {
                    holiday = "大雪";
                    is = true;
                } else if (t == solartime[21]) {
                    holiday = "冬至";
                    is = true;
                }
                break;
            case 1:
                if (t == solartime[22]) {
                    holiday = "小寒";
                    is = true;
                } else if (t == solartime[23]) {
                    holiday = "大寒";
                    is = true;
                }
                break;
        }
        switch (t) {
            case 101:
                holiday = "元旦";
                isRed = true;
                is = true;
                break;
            case 214:
                holiday = "情人节";
                is = true;
                break;
            case 308:
                holiday = "妇女节";
                is = true;
                break;
            case 312:
                holiday = "植树节";
                is = true;
                break;
            case 315:
                holiday = "消费日";
                is = true;
                break;
            case 401:
                holiday = "愚人节";
                is = true;
                break;
            // case 407:
            // holiday="卫生日";
            // is=true;
            // break;
            case 501:
                holiday = "劳动节";
                is = true;
                break;
            case 504:
                holiday = "青年节";
                is = true;
                break;
            // case 512:
            // holiday="护士节";
            // is=true;
            // break;
            // case 513:
            // holiday="助残日";
            // is=true;
            // break;

            case 601:
                holiday = "儿童节";
                is = true;
                break;
            case 605:
                holiday = "世界环境日";
                is = true;
                break;
            case 701:
                holiday = "建党节";
                is = true;
                break;
            case 801:
                holiday = "建军节";
                is = true;
                break;
            case 910:
                holiday = "教师节";
                is = true;
                break;
            case 1001:
                holiday = "国庆节";
                is = true;
                break;
            case 1225:
                holiday = "圣诞节";
                is = true;
                break;
            default:
                // is=false;
                break;
        }

        return is;
    }

    String Today = "";

    @SuppressWarnings("deprecation")
    public void GenView() {
        dataLinear.removeAllViews();
        mLayoutParamss.weight = 1;
        LayoutInflater lif = LayoutInflater.from(context);
        LinearLayout temp = new LinearLayout(context);
        int size = data.size();
        for (int i = 0; i < size; i++) {
            View convertView = lif.inflate(R.layout.gritem, null);
            TextView time = (TextView) convertView.findViewById(R.id.time);
            TextView lunar = (TextView) convertView.findViewById(R.id.lunar);
            TextView fraction = (TextView) convertView.findViewById(R.id.fraction);
            LinearLayout itemroot = (LinearLayout) convertView.findViewById(R.id.itemroot);
            HashMap<String, String> map = data.get(i);
            if ((i + 1) < size) {
                HashMap<String, String> map2 = data.get(i + 1);
                if (map2.get("lunar").equals("春节")) {
                    map.put("lunar", "除夕");
                }
            }
            String day = map.get("day");
            if (map.get("isMonth").equals("1"))// 1是本月
            {
                itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                if (map.get("isToday").equals("1"))// 1是今天
                {
                    time.setTextColor(getResources().getColor(R.color.sunday_txt));
                    lunar.setTextColor(getResources().getColor(R.color.sunday_txt));
//                    itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity_jintian));
                } else {
                    itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                }
                if (ToMonth.equals(standard_month > 9 ? standard_month : "0" + standard_month)) {
                    if (Today.equals("" + (Integer.parseInt(day) > 9 ? day : "0" + day))) {
//                        time.setTextColor(getResources().getColor(R.color.sunday_txt));
//                        lunar.setTextColor(getResources().getColor(R.color.sunday_txt));
                        itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity_jintian));
                    } else {
                        itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                    }
                }
//                int m = (i + 1) % 7;
//                if (m == 1 || m == 0) {
//                    time.setTextColor(Color.rgb(50, 79, 133));
//                }
                if (map.get("isHoliday").equals("1")) // 节日
                {
                    time.setTextColor(Color.RED);
                }
                itemroot.setTag(R.id.calendar_index, "1");//0其他,1是本月
            } else {
                time.setTextColor(getResources().getColor(R.color.othermonth_txt));
                lunar.setTextColor(getResources().getColor(R.color.othermonth_txt));
                itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                itemroot.setTag(R.id.calendar_index, "0");
            }

            String datestr = standard_year + "-" +
                    (standard_month > 9 ? standard_month : "0" + standard_month) + "-" +
                    (day.length() > 1 ? day : "0" + day);
            if (map.get("isMonth").equals("1")) {// 1是本月
                if (App.getDBcApplication().queryISNOTHOLIDAY(datestr).equals("1")) {//休息
                    fraction.setText("休");
                    fraction.setTextColor(getResources().getColor(R.color.sunday_txt));
                } else if (App.getDBcApplication().queryISNOTHOLIDAY(datestr).equals("2")) {//上班
                    fraction.setText("班");
                    fraction.setTextColor(getResources().getColor(R.color.title0));
                } else {
                    fraction.setVisibility(View.GONE);
                }
            }
            if (!map.get("isMonth").equals("1")) {
                time.setVisibility(View.GONE);
                fraction.setVisibility(View.GONE);
                lunar.setVisibility(View.GONE);
            }
            time.setText(day);
            lunar.setText(map.get("lunar"));
            itemroot.setTag(day);
            itemroot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String day = v.getTag().toString();
                    // 0其他,1是本月
                    String calendar_index = v.getTag(R.id.calendar_index)
                            .toString();
                    if ("1".equals(calendar_index)) {
                        String dateTime = Integer.toString(standard_year)
                                + "-"
                                + (standard_month > 9 ? "" + standard_month
                                : "0" + standard_month) + "-"
                                + (Integer.parseInt(day) > 9 ? day : "0" + day);
                        Message message = new Message();
                        message.what = 9;
                        message.obj = "\"" + dateTime + "\"\n设置日期";
                        Today = dateTime;
                        handlerrili.sendMessage(message);
                    }
                }
            });
            if ((i + 1) % 7 != 0) {
                temp.addView(convertView, mLayoutParamss);
            } else {
                if (i != 0) {
                    temp.addView(convertView, mLayoutParamss);
                    dataLinear.addView(temp, mLayoutParamss);
                    temp = new LinearLayout(context);
                }
            }
        }
    }

    /*
     * 基姆拉尔森计算公式 QgW4jIbx W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7 /
     *
     * d 天 m 月 y 年 1月2月换算为去年的13 14月计算
     *
     * 基姆拉尔森计算公式的C#的实现 %NfbgJcL_ //y：年，m：月，d：日。在参数都只传入相应的整数
     */
    private int calWeek(int y, int m, int d) {
        int a = 7; // 用来保存计算得到的星期几的整数 Dz>v;%$S-
        if ((m == 1) || (m == 2))// 如果是一月或二月进行换算 uWKc .
        {
            m += 12;
            y--;
        }
        a = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7; // 得到的星期几的整数
        // 
        // 7ehs+GI
        a++;
        if (a == 7) {
            a = 0;
        }
        return a;
    }

    public void calLeapYear(int i) {
        if (i % 100 == 0) {
            if (i % 400 == 0) {
                isLeap = true;
            } else {
                isLeap = false;
            }
        } else {
            if (i % 4 == 0) {
                isLeap = true;
            } else {
                isLeap = false;
            }
        }
    }

    Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
    private LinearLayout ll;
    private TextView tixingcishu_tv;

    int indexti = 0;
    GridBeforeAdapter adapterti = null;


    private void initMap() {
        for (int i = 1; i < 9; i++) {
            if (i == indexti) {
                map.put(i, true);
            } else {
                map.put(i, false);
            }
        }
    }

    private void initMap1() {
        for (int i = 1; i < 9; i++) {
            map.put(i, false);
        }
    }

    int isAlarm = 0;

    public class GridBeforeAdapter extends BaseAdapter {

        private Context context;
        private String[] beforeTime;
        private int height;
        private int lastIndex;
        String str = "一次提醒";
        TextView tixing, tixingcishu_tv;
        Map<String, String> mMap;

        public GridBeforeAdapter(Context context, String[] beforeTime,
                                 int height, int lastIndex, TextView tixing, TextView tixingcishu_tv, Map<String, String> mMap) {
            this.context = context;
            this.beforeTime = beforeTime;
            this.height = height;
            this.lastIndex = lastIndex;
            this.tixing = tixing;
            this.tixingcishu_tv = tixingcishu_tv;
            this.mMap = mMap;
            initMap();
        }

        @Override
        public int getCount() {
            return beforeTime.length;
        }

        @Override
        public Object getItem(int position) {
            return beforeTime[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public String[] getBeforeTime() {
            return beforeTime;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            View view = convertView;
            ViewWapper viewWapper = null;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(
                        R.layout.adapter_grid_before_item, null);
                viewWapper = new ViewWapper(view);
                view.setTag(viewWapper);
            } else {
                viewWapper = (ViewWapper) view.getTag();
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, height);
            LinearLayout before_ll = viewWapper.getBeforLL();
            before_ll.setLayoutParams(params);

            TextView before_tv = viewWapper.getBeforTime();
            TextView before_tv_state = viewWapper.getBeforState();
            String beforTime = beforeTime[position];
            if (str.equals("一次提醒")) {
                str = "准时提醒";
            }
            if (beforTime.equals(str)) {
                before_tv.setText(beforTime);
                before_tv.setTextSize(15);
            } else {
                before_tv.setText(beforTime.split("-")[0]);
                before_tv_state.setText(beforTime.split("-")[1]);
            }


            before_ll.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (position == 0) {
                        if (map.get(0)) {
                            map.put(position, false);
                        } else {
                            map.put(position, true);
                        }
                    } else {
                        if (position == lastIndex) {
                            if (map.get(position)) {
                                map.put(position, false);
                            } else {
                                map.put(position, true);
                            }
                        } else {
                            initMap1();
                            map.put(position, true);
                        }

                        lastIndex = position;
                    }

                    adapterti.notifyDataSetChanged();

                    int before = 0;
                    if (map.get(0)) {
                        before = 0;
                    }
                    if (map.get(1)) {
                        before = 5;
                    } else if (map.get(2)) {
                        before = 15;
                    } else if (map.get(3)) {
                        before = 30;
                    } else if (map.get(4)) {
                        before = 60;
                    } else if (map.get(5)) {
                        before = 120;
                    } else if (map.get(6)) {
                        before = 24 * 60;
                    } else if (map.get(7)) {
                        before = 48 * 60;
                    } else if (map.get(8)) {
                        before = 7 * 24 * 60;
                    }

                    int select = 0;
                    for (int i = 0; i < beforeTime.length; i++) {
                        if (map.get(i)) {
                            select++;
                        }
                    }

                    if (select == 1) {
                        tixingcishu_tv.setText("一次提醒");
                    } else if (select == 2) {
                        tixingcishu_tv.setText("两次提醒");
                    }

                    if (position == 0) {
                        if (map.get(0)) {
                            if (select == 1) {
                                mMap.put(ScheduleTable.schIsAlarm, "1");
                                mMap.put(ScheduleTable.schBeforeTime, "0");
                                App.getDBcApplication().updateSceduleDataTiQianTime(Integer.valueOf(mMap.get(ScheduleTable.schID)), 0, 1);
                            } else if (select == 2) {
                                mMap.put(ScheduleTable.schIsAlarm, "3");
                                mMap.put(ScheduleTable.schBeforeTime, before + "");
                                App.getDBcApplication().updateSceduleDataTiQianTime(Integer.valueOf(mMap.get(ScheduleTable.schID)), before, 3);
                            }
                        } else {
                            if (select == 1) {
                                mMap.put(ScheduleTable.schIsAlarm, "2");
                                mMap.put(ScheduleTable.schBeforeTime, before + "");
                                App.getDBcApplication().updateSceduleDataTiQianTime(Integer.valueOf(mMap.get(ScheduleTable.schID)), before, 2);
                            }
                        }
                    } else {
                        if (map.get(position)) {
                            if (select == 1) {
                                mMap.put(ScheduleTable.schIsAlarm, "2");
                                mMap.put(ScheduleTable.schBeforeTime, before + "");
                                App.getDBcApplication().updateSceduleDataTiQianTime(Integer.valueOf(mMap.get(ScheduleTable.schID)), before, 2);
                            } else if (select == 2) {
                                mMap.put(ScheduleTable.schIsAlarm, "3");
                                mMap.put(ScheduleTable.schBeforeTime, before + "");
                                App.getDBcApplication().updateSceduleDataTiQianTime(Integer.valueOf(mMap.get(ScheduleTable.schID)), before, 3);
                            }
                        } else {
                            if (select == 1) {
                                mMap.put(ScheduleTable.schIsAlarm, "1");
                                mMap.put(ScheduleTable.schBeforeTime, "0");
                                App.getDBcApplication().updateSceduleDataTiQianTime(Integer.valueOf(mMap.get(ScheduleTable.schID)), 0, 1);
                            }
                        }
                    }
                    if (Integer.valueOf(mMap.get(ScheduleTable.schIsAlarm)) == 0 || Integer.valueOf(mMap.get(ScheduleTable.schIsAlarm)) == 1) {
                        beforeType = "准时提醒";
                        isAlarm = 1;
                        //有提前
                    } else if (Integer.valueOf(mMap.get(ScheduleTable.schIsAlarm)) == 2) {
                        isAlarm = 2;
                        if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 5) {
                            beforeType = "提前5分钟";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 15) {
                            beforeType = "提前15分钟";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 30) {
                            beforeType = "提前30分钟";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 60) {
                            beforeType = "提前1小时";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 120) {
                            beforeType = "提前2小时";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 24 * 60) {
                            beforeType = "提前1天";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 48 * 60) {
                            beforeType = "提前2天";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 7 * 24 * 60) {
                            beforeType = "提前1周";
                        }
                        //准时+提前
                    } else if (Integer.valueOf(mMap.get(ScheduleTable.schIsAlarm)) == 3) {
                        isAlarm = 3;
                        if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 5) {
                            beforeType = "准时提醒\n提前5分钟";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 15) {
                            beforeType = "准时提醒\n提前15分钟";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 30) {
                            beforeType = "准时提醒\n提前30分钟";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 60) {
                            beforeType = "准时提醒\n提前1小时";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 120) {
                            beforeType = "准时提醒\n提前2小时";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 24 * 60) {
                            beforeType = "准时提醒\n提前1天";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 48 * 60) {
                            beforeType = "准时提醒\n提前2天";
                        } else if (Integer.valueOf(mMap.get(ScheduleTable.schBeforeTime)) == 7 * 24 * 60) {
                            beforeType = "准时提醒\n提前1周";
                        }
                    }

                    int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");


                    loadData(2, mMap.get(ScheduleTable.schID));
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();

                }
            });

            int select = 0;
            for (int i = 0; i < beforeTime.length; i++) {
                if (map.get(i)) {
                    select++;
                }
            }
            if (position == 0) {
                if (map.get(position)) {
                    before_ll.setBackgroundColor(getResources().getColor(
                            R.color.sunday_txt));
                    before_tv.setTextColor(getResources().getColor(
                            R.color.white));

                } else {
                    before_ll.setBackgroundColor(getResources().getColor(
                            R.color.choosedate));
                    before_tv.setTextColor(getResources().getColor(
                            R.color.gongkai_txt));
                }
            } else {
                if (map.get(position)) {
                    before_ll.setBackgroundColor(getResources().getColor(
                            R.color.mingtian_color));
                    before_tv.setTextColor(getResources().getColor(
                            R.color.white));
                    before_tv_state.setTextColor(getResources().getColor(
                            R.color.white));
                } else {
                    before_ll.setBackgroundColor(getResources().getColor(
                            R.color.choosedate));
                    before_tv.setTextColor(getResources().getColor(
                            R.color.gongkai_txt));
                    before_tv_state.setTextColor(getResources().getColor(
                            R.color.gongkai_txt));
                }
            }


            String selecttime = "";
            if ("全天".equals(mMap.get(ScheduleTable.schTime))) {
                selecttime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ALLTIME, "23:59");
            } else {
                selecttime = mMap.get(ScheduleTable.schTime);
            }
            if (select == 1) {
                ll.setVisibility(View.VISIBLE);
                if (map.get(0)) {
                    tixing.setText("\"一次提醒\"");
                    isAlarm = 1;
                } else {
                    if (map.get(position)) {
                        isAlarm = 2;
                        tixing.setText("\"一次提醒\"");
                    }
                }
            } else if (select == 2) {
                ll.setVisibility(View.VISIBLE);
//                tixing_ll.setVisibility(View.VISIBLE);
                isAlarm = 3;
                tixing.setText("\"两次提醒\"");
            } else {
                map.put(0, true);
                ll.setVisibility(View.VISIBLE);
                tixing.setText("\"一次提醒\"");
            }
            return view;
        }

        class ViewWapper {

            private View view;
            private LinearLayout before_ll;
            private TextView before_tv;
            private TextView before_state;

            private ViewWapper(View view) {
                this.view = view;
            }

            private LinearLayout getBeforLL() {
                if (before_ll == null) {
                    before_ll = (LinearLayout) view
                            .findViewById(R.id.before_ll);
                }
                return before_ll;
            }

            private TextView getBeforTime() {
                if (before_tv == null) {
                    before_tv = (TextView) view.findViewById(R.id.before_tv);
                }
                return before_tv;
            }

            private TextView getBeforState() {
                if (before_state == null) {
                    before_state = (TextView) view
                            .findViewById(R.id.before_state);
                }
                return before_state;
            }
        }
    }

    class ViewAdapter extends PagerAdapter {
        private List<View> viewList;//数据源

        public ViewAdapter(List<View> viewList) {
            this.viewList = viewList;
        }

        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position));
            return viewList.get(position);
        }
    }

    private void updateDeleteScheduleRead(Map<String, String> mMap, String key,
                                          String key1) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            if ("0".equals(mMap.get(key)))
                value = "0";
            else
                value = "0";
            upMap.put(key, value);
            upMap.put(key1, "2");
            App.getDBcApplication().updateScheduleData(upMap, "where schID=" + mMap.get("schID"));
            mMap.put(key, value);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateScheduleRead1(Map<String, String> mMap, String key) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            value = mMap.get(ScheduleTable.schRead);
            upMap.put(key, value);
            App.getDBcApplication().updateScheduleData1(upMap, "where schID=" + mMap.get("schID"));
            mMap.put(key, value);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateScheduleRead2(Map<String, String> mMap, String key,
                                     String key1) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            value = mMap.get(key);
            upMap.put(key, value);
            upMap.put(key1, "3");
            App.getDBcApplication().updateScheduleData(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateSchedule(Map<String, String> mMap, String key,
                                String key1) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            if ("0".equals(mMap.get(key)))
                value = "1";
            else
                value = "0";
            upMap.put(key, value);
            if (!"0".equals(upMap.get(ScheduleTable.schAID))) {
                upMap.put(key1, "2");
            } else {
                upMap.put(key1, "2");
            }
            App.getDBcApplication().updateScheduleData(upMap,
                    "where schID=" + mMap.get("schID"));
            mMap.put(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateScheduleIsEnd(Map<String, String> mMap, String key,
                                     String key1) {
        try {
            if ("1".equals(mMap.get(ScheduleTable.schRepeatLink)) || "3".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                repeatSetChildEndUtils.setParentStateIsEnd(mMap);
            }
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            if ("0".equals(mMap.get(key)))
                value = "1";
            else
                value = "0";
            upMap.put(key, value);
            if ("1".equals(mMap.get(ScheduleTable.schRepeatLink))
                    || "3".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                upMap.put(key1, "0");
            } else {
                upMap.put(key1, "2");
            }
            App.getDBcApplication().updateScheduleData(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        loadData(2, mMap.get(ScheduleTable.schID));
    }

    private void updateRepSchUpdate(Map<String, String> mMap, String key,
                                    String key1) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            if ("0".equals(mMap.get(key)))
                value = "1";
            else
                value = "0";
            upMap.put(key, value);
            if (!"0".equals(upMap.get(ScheduleTable.schAID))) {
                upMap.put(key1, "1");
            } else {
                upMap.put(key1, "1");
            }
            App.getDBcApplication().updateScheduleData(upMap,
                    "where schID=" + mMap.get("schID"));
            mMap.put(key, value);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateFocusStateSch(Map<String, String> mMap, String key) {
        try {
            Map<String, String> upMap = new HashMap<String, String>();
            upMap.put(key, "1");
            App.getDBcApplication().updateSchFocusState(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateSchClock(Map<String, String> mMap, String key) {
        try {
            String value = "0";
            String key1 = "";
            Map<String, String> upMap = new HashMap<String, String>();
            if (key.equals("isEnd")) {
                key1 = "schIsEnd";
            } else if (key.equals("postpone")) {
                key1 = "schIsPostpone";
            }
            if ("1".equals(mMap.get(key1)))
                value = "1";
            else
                value = "0";
            upMap.put(key, value);
            App.getDBcApplication().updateSchIsEnd(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    PopupWindow popupWindow;

    private void addBtnImageButton() {
        View view = LayoutInflater.from(context).inflate(R.layout.home_add_popup, null);
        popupWindow = new PopupWindow(view,
                Utils.dipTopx(context, 100),
                Utils.dipTopx(context, 162));
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = view.getMeasuredWidth();    //  获取测量后的宽度
        int popupHeight = view.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        add_btn_image.getLocationOnScreen(location);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//        popupWindow.showAsDropDown(add_btn_image,-20, -Utils.dipTopx(context, 200));
        popupWindow.showAtLocation(add_btn_image,
                Gravity.NO_GRAVITY,
                (location[0] + add_btn_image.getWidth() / 2) - popupWidth / 2 - Utils.dipTopx(context, 34),
                location[1] - popupHeight + Utils.dipTopx(context, 10));
        view.findViewById(R.id.more).setOnClickListener(v -> {
            popupWindow.dismiss();
            dialogOnClick();
        });
        view.findViewById(R.id.daiban).setOnClickListener(v -> {
            popupWindow.dismiss();
            CalenderAddDContentDialog dialog = new CalenderAddDContentDialog(context, R.style.dialog_translucent, getActivity().getWindowManager());
            dialog.show();
            dialog.setCallBack(new CalenderAddDContentDialog.CallBack() {
                @Override
                public void save() {
                    Message message = new Message();
                    message.what = 8;
                    handler.sendMessage(message);
                }

                @Override
                public void full(String content) {
                    Intent intent = new Intent(context, CalenderNoteEditActivity.class);
                    intent.putExtra("newadd", true);
                    intent.putExtra("newopeartType", 0);
                    intent.putExtra("content", content);
                    context.startActivity(intent);
                }
            });
        });
        view.findViewById(R.id.richeng).setOnClickListener(v -> {
            popupWindow.dismiss();
            CalenderAddCContentDialog dialog = new CalenderAddCContentDialog(context, R.style.dialog_translucent, getActivity().getWindowManager());
            dialog.show();
            dialog.setCallBack(new CalenderAddCContentDialog.CallBack() {
                @Override
                public void save() {
                    Message message = new Message();
                    message.what = 8;
                    handler.sendMessage(message);
                }

                @Override
                public void full(String content) {
                }
            });
        });
    }

    private void itemMore(Map<String, String> mMaps, int setType, final int position) {

        final Map<String, String> mMap = mMaps;
        List<View> viewList = new ArrayList<View>();

        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String today = DateUtil.formatDate(calendar.getTime());
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.get(Calendar.DAY_OF_MONTH) + 1);
        String tomorrow = DateUtil.formatDate(calendar.getTime());

        final int id = Integer.parseInt(mMap.get(ScheduleTable.schID));


        final Map<String, String> map = App.getDBcApplication().QueryStateData(
                Integer.parseInt(mMap.get(ScheduleTable.schRepeatID)));

        final Intent intent = new Intent();

        final MySchBean mySchBean = new MySchBean();
        mySchBean.schID = mMap.get(ScheduleTable.schID);
        mySchBean.schContent = mMap.get(ScheduleTable.schContent);
        mySchBean.schDate = mMap.get(ScheduleTable.schDate);
        mySchBean.schTime = mMap.get(ScheduleTable.schTime);
        mySchBean.schIsAlarm = mMap.get(ScheduleTable.schIsAlarm);
        mySchBean.schBeforeTime = mMap.get(ScheduleTable.schBeforeTime);
        mySchBean.schDisplayTime = mMap.get(ScheduleTable.schDisplayTime);
        mySchBean.schIsPostpone = mMap.get(ScheduleTable.schIsPostpone);
        mySchBean.schIsImportant = mMap.get(ScheduleTable.schIsImportant);
        mySchBean.schColorType = mMap.get(ScheduleTable.schColorType);
        mySchBean.schIsEnd = mMap.get(ScheduleTable.schIsEnd);
        mySchBean.schCreateTime = mMap.get(ScheduleTable.schCreateTime);
        mySchBean.schTags = mMap.get(ScheduleTable.schTags);
        mySchBean.schSourceType = mMap.get(ScheduleTable.schSourceType);
        mySchBean.schSourceDesc = mMap.get(ScheduleTable.schSourceDesc);
        mySchBean.schSourceDescSpare = mMap.get(ScheduleTable.schSourceDescSpare);
        mySchBean.schRepeatID = mMap.get(ScheduleTable.schRepeatID);
        mySchBean.schRepeatDate = mMap.get(ScheduleTable.schRepeatDate);
        mySchBean.schUpdateTime = mMap.get(ScheduleTable.schUpdateTime);
        mySchBean.schUpdateState = mMap.get(ScheduleTable.schUpdateState);
        mySchBean.schOpenState = mMap.get(ScheduleTable.schOpenState);
        mySchBean.schRepeatLink = mMap.get(ScheduleTable.schRepeatLink);
        mySchBean.schRingDesc = mMap.get(ScheduleTable.schRingDesc);
        mySchBean.schRingCode = mMap.get(ScheduleTable.schRingCode);
        mySchBean.schcRecommendName = mMap.get(ScheduleTable.schcRecommendName);
        mySchBean.schRead = mMap.get(ScheduleTable.schRead);
        int colortype = Integer.parseInt(mMap.get(ScheduleTable.schColorType));
        final String colorname = application.QueryTagNameData(colortype).get("ctgText");
        View view = LayoutInflater.from(context).inflate(R.layout.home_stay_popup, null);
        View top = view.findViewById(R.id.top);
        View down = view.findViewById(R.id.down);
        TextView more = view.findViewById(R.id.more);
        TextView important = view.findViewById(R.id.important);
        TextView move = view.findViewById(R.id.move);
        LinearLayout tl = view.findViewById(R.id.tl);
        if ("0".equals(mMap.get(ScheduleTable.schIsImportant))) {
            important.setText("设为重要");
        } else {
            important.setText("取消重要");
        }
        if (setType == 1) {
            move.setText("移到待办");
            tl.setVisibility(View.VISIBLE);
        }
        final LinearLayout stay_1 = view.findViewById(R.id.stay_1);
        final LinearLayout stay_2 = view.findViewById(R.id.stay_2);

        popupWindow = new PopupWindow(view,
                Utils.dipTopx(context, 100),
                Utils.dipTopx(context, setType == 1 ? 256 : 209));
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int windowHeight = view.getMeasuredHeight();
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int x = App.get(context).pointV.getHeight() - (int) App.get(context).pointY;
        if (App.get(context).rawY + windowHeight > ScreenUtils.getScreenHeight(context)) {
            down.setVisibility(View.VISIBLE);
            top.setVisibility(View.GONE);
            x = windowHeight + (int) (App.get(context).viewH - App.get(context).pointY);
        } else {
            down.setVisibility(View.GONE);
            top.setVisibility(View.VISIBLE);
        }
        popupWindow.showAsDropDown(App.get(context).pointV,
                (int) App.get(context).pointX - Utils.dipTopx(context, 50), -x);
        int nx = x;
        more.setOnClickListener(v -> {
            stay_1.setVisibility(stay_1.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            stay_2.setVisibility(stay_2.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            more.setText(stay_1.getVisibility() == View.VISIBLE ? "更多" : "返回");
            if (setType == 1) {
                popupWindow.dismiss();
                if (stay_1.getVisibility() == View.VISIBLE) {
                    popupWindow.showAsDropDown(App.get(context).pointV,
                            (int) App.get(context).pointX - Utils.dipTopx(context, 50), -nx);
                } else {
                    popupWindow.showAsDropDown(App.get(context).pointV,
                            (int) App.get(context).pointX - Utils.dipTopx(context, 50), -nx + Utils.dipTopx(context, 47));
                }
            }
        });
        move.setOnClickListener(v -> {

            if (setType == 1) {
                App.getDBcApplication().updateScheduleUnTaskData(mMap.get(ScheduleTable.schID));
                updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                App.getDBcApplication().updateSchReadData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                App.getDBcApplication().updateSchRepeatLinkData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, mMap.get(ScheduleTable.schID));
                loadData(3, "");
                QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                UpLoadData();
                Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                Bundle extras = new Bundle();
                intentf.putExtras(extras);
                getActivity().sendBroadcast(intentf);
            } else {
                RiLiDialog dialog = new RiLiDialog(context, R.style.dialog_translucent, getActivity().getWindowManager());
                dialog.show();
                dialog.setCallBack(date -> {
                    try {
                        updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                        App.getDBcApplication().updateScheduleDateData(id, date, mMap.get(ScheduleTable.schTime));
                        App.getDBcApplication().updateSchReadData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                        App.getDBcApplication().updateSchRepeatLinkData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                        if (!"".equals(mMap.get(ScheduleTable.schRepeatDate)) || !"0".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                            if (map != null) {
                                String repdate = mMap.get(ScheduleTable.schRepeatDate);
                                String lastdate = StringUtils.getIsStringEqulesNull(map.get(CLRepeatTable.repDateOne));
                                String nextdate = StringUtils.getIsStringEqulesNull(map.get(CLRepeatTable.repDateTwo));
                                repeatSetChildEndUtils.setParentState(Integer.parseInt(mMap.get(ScheduleTable.schRepeatID)), repdate, nextdate, lastdate, map);
                            }
                        }
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, mMap.get(ScheduleTable.schID));
                        loadData(3, "");
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                        UpLoadData();
                        Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentf.putExtras(extras);
                        getActivity().sendBroadcast(intentf);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dialog.dismiss();
                });
            }


            popupWindow.dismiss();
        });
        tl.setOnClickListener(v -> {
            RiLiDialog dialog = new RiLiDialog(context, R.style.dialog_translucent, getActivity().getWindowManager());
            dialog.show();
            dialog.setCallBack(date -> {
                try {
                    updateFocusStateSch(mMap, ScheduleTable.schFocusState);
                    App.getDBcApplication().updateScheduleDateData(id, date, mMap.get(ScheduleTable.schTime));
                    App.getDBcApplication().updateSchReadData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    App.getDBcApplication().updateSchRepeatLinkData(Integer.parseInt(mMap.get(ScheduleTable.schID)), 0);
                    if (!"".equals(mMap.get(ScheduleTable.schRepeatDate)) || !"0".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                        if (map != null) {
                            String repdate = mMap.get(ScheduleTable.schRepeatDate);
                            String lastdate = StringUtils.getIsStringEqulesNull(map.get(CLRepeatTable.repDateOne));
                            String nextdate = StringUtils.getIsStringEqulesNull(map.get(CLRepeatTable.repDateTwo));
                            repeatSetChildEndUtils.setParentState(Integer.parseInt(mMap.get(ScheduleTable.schRepeatID)), repdate, nextdate, lastdate, map);
                        }
                    }
                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, mMap.get(ScheduleTable.schID));
                    loadData(3, "");
                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                    UpLoadData();
                    Intent intentf = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    Bundle extras = new Bundle();
                    intentf.putExtras(extras);
                    getActivity().sendBroadcast(intentf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            });
            popupWindow.dismiss();
        });
        important.setOnClickListener(v -> {
            popupWindow.dismiss();
            if ("0".equals(mMap.get(ScheduleTable.schIsImportant))) {
//                    important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_lv));
                important.setText("取消重要");
                mMap.put(ScheduleTable.schIsImportant, "1");
                App.getDBcApplication().updatImportant(1, mMap.get(ScheduleTable.schID));
            } else {
//                    important_image.setBackground(getResources().getDrawable(R.mipmap.anniu_zhongyao_hui));
                important.setText("设为重要");
                App.getDBcApplication().updatImportant(0, mMap.get(ScheduleTable.schID));
                mMap.put(ScheduleTable.schIsImportant, "0");
            }
            try {
                loadData(2, mMap.get(ScheduleTable.schID));
                adapter.notifyDataSetChanged();
                QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                UpLoadData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        view.findViewById(R.id.copy).setOnClickListener(v -> {
            popupWindow.dismiss();
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(mMap.get(ScheduleTable.schContent));
            Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });
        view.findViewById(R.id.copyx).setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        view.findViewById(R.id.type).setOnClickListener(v -> {
            popupWindow.dismiss();
            try {
                CalenderFlagDialog calenderFlagDialog = new CalenderFlagDialog(context, R.style.dialog_translucent,
                        getActivity().getWindowManager(), mMap.get(ScheduleTable.schID), colorname, "");
                calenderFlagDialog.setCallBack((name, id1) -> {
//                            loadData(true);
                    loadData(2, mMap.get(ScheduleTable.schID));
                });
                calenderFlagDialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        view.findViewById(R.id.color_pen).setOnClickListener(v -> {
            popupWindow.dismiss();
            CalenderColorDialog colorDialog = new CalenderColorDialog(context, R.style.dialog_translucent,
                    getActivity().getWindowManager(), mMap.get(ScheduleTable.schID), 1);
            colorDialog.show();
            colorDialog.setCallBack((color_position_f, color_position) -> {
                loadData(2, mMap.get(ScheduleTable.schID));
                adapter.notifyDataSetChanged();
            });
        });
    }


    Dialog baseDialog;

    /**
     * 点击添加时的对话框
     */
    private void dialogOnClick() {
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APPWIDGETUPLOADTYPE, "0");
        Context context = getActivity();
        baseDialog = new Dialog(context, R.style.dialog_translucent);
        Window window = baseDialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
//        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        final RelativeLayout view = (RelativeLayout) fac.inflate(R.layout.dialog_calender_new_add, null);
        baseDialog.setCanceledOnTouchOutside(true);
        baseDialog.setContentView(view);
        params.height = DisplayUtils.dipToPix(context, 400);
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth() - 30;

        showAnimation(view);

        baseDialog.show();

        new MyGeneralOnClick(baseDialog, view);
    }

    private void showAnimation(final ViewGroup layout) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < layout.getChildCount(); i++) {
                    final View child = layout.getChildAt(i);
                    child.setVisibility(View.INVISIBLE);
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            child.setVisibility(View.VISIBLE);
                            ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 600f, 0f);
                            fadeAnim.setDuration(400);
                            KickBackAnimator kickAnimator = new KickBackAnimator();
                            kickAnimator.setDuration(300);
                            fadeAnim.setEvaluator(kickAnimator);
                            fadeAnim.start();
                        }
                    }, i * 50);
                }
            }
        }, 200);
    }


    private void debean(String titleId, int orderid, String content, String titles, boolean isCopyType) {
        CalenderNoteBean.PageBean.ItemsBean bean = new CalenderNoteBean.PageBean.ItemsBean();
        bean.titleId = titleId;
        bean.uid = Integer.valueOf(userid);
        bean.id = App.getDBcApplication().getCalenderMinId() - 1;
        bean.style = 3;//isCopyType ? 0 :
        bean.changeTime = DateUtil.nowTime();
        bean.createTime = DateUtil.nowTime();
        bean.ltype = 0;
        bean.orderId = orderid;
        bean.endstate = 0;
        bean.remark = "";
        bean.contents = content;
        bean.titles = titles;
        bean.imgPath = "";
        bean.imgUrl = "";
        bean.cpath = "";
        bean.curl = "";
        bean.sdesc = "";
        bean.nums = "";
        bean.localIds = DateUtil.nowTime2();
        bean.shareUrl = "";
        bean.remark1 = "";
        bean.remark2 = "";
        bean.remark3 = "";
        bean.remark4 = "";
        bean.remark5 = "";
        bean.remark6 = "";

        App.getDBcApplication().saveCalederNoteDetailData(bean);
        App.getDBcApplication().updateCalenderNoteDetailState(titleId, bean.id, userid, 1, true);

    }

    class MyGeneralOnClick implements OnClickListener, OnTouchListener {

        private RelativeLayout view;
        private Dialog dialog;
        private ImageView yuyin;
        private TextView zidingyi_tv;
        private TextView changyong_tv;
        private TextView copy_tv, daoqiri;

        @SuppressLint("NewApi")
        public MyGeneralOnClick(Dialog dialog, RelativeLayout view) {
            this.dialog = dialog;
            this.view = view;
            initview();
        }

        private void initview() {
            yuyin = (ImageView) view.findViewById(R.id.yuyin);
            yuyin.setOnTouchListener(this);
            zidingyi_tv = (TextView) view.findViewById(R.id.zidingyi_tv);
            zidingyi_tv.setOnClickListener(this);
            changyong_tv = (TextView) view.findViewById(R.id.changyong_tv);
            changyong_tv.setOnClickListener(this);
            daoqiri = (TextView) view.findViewById(R.id.daoqiri);
            daoqiri.setOnClickListener(this);
            copy_tv = (TextView) view.findViewById(R.id.copy_tv);
            copy_tv.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.copy_tv:
//                    ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
//                    if (clipboardManager.getText() == null) {
//                        alertClipIsEmptry();
//                    } else {
//                        String titleId = DateUtil.nowTime2();
//                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
//                        String content = clipboardManager.getText().toString();
//                        if (content.length() > 1) {
//                            if (content.substring(0, 2).equals("**")) {
//                                String[] notecontent = content.substring(1, content.length()).split("\\*");
//                                if (notecontent.length >= 2) {
//                                    String[] conde = notecontent[notecontent.length - 1].split("\n");
//                                    String title = notecontent[0];
//                                    for (int i = 0; i < notecontent.length - 1; i++) {
//                                        if (!notecontent[i].isEmpty()) {
//                                            title = notecontent[i];
//                                        }
//                                    }
//                                    String before = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
//                                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
//                                    App.getDBcApplication().insertScheduleData(title, DateUtil.formatDate(new Date()),
//                                            DateUtil.formatDateTimeHm(new Date()), 1,
//                                            Integer.parseInt(before), 0, 1, 0,
//                                            0, 0, DateUtil.formatDateTime(new Date()), "", 0,
//                                            titleId, "", 0, "", DateUtil.formatDateTime(new Date()),
//                                            1, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "",
//                                            "", 0, 0, 0, 0, "", "0", "0");
//                                    int i = 0;
//                                    for (String item : conde) {
//                                        if (!item.isEmpty()) {
//                                            debean(titleId, i, item, title, false);
//                                            i++;
//                                        } else {
//                                            continue;
//                                        }
//                                    }
//                                } else if (notecontent.length == 1) {
//                                    String before = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
//                                    sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
//                                    App.getDBcApplication().insertScheduleData(notecontent[0], DateUtil.formatDate(new Date()),
//                                            DateUtil.formatDateTimeHm(new Date()), 1,
//                                            Integer.parseInt(before), 0, 1, 0,
//                                            0, 0, DateUtil.formatDateTime(new Date()), "", 0,
//                                            titleId, "", 0, "", DateUtil.formatDateTime(new Date()),
//                                            1, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "",
//                                            "", 0, 0, 0, 0, "", "0", "0");
//                                }
//                            } else {
//                                String[] conde = content.split("\n");
//                                String before = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
//                                sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
//                                App.getDBcApplication().insertScheduleData(conde[0], DateUtil.formatDate(new Date()),
//                                        DateUtil.formatDateTimeHm(new Date()), 1,
//                                        Integer.parseInt(before), 0, 1, 0,
//                                        0, 0, DateUtil.formatDateTime(new Date()), "", 0,
//                                        titleId, "", 0, "", DateUtil.formatDateTime(new Date()),
//                                        1, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "",
//                                        "", 0, 0, 0, 0, "", "0", "0");
//                                if (conde.length > 2) {
//                                    int i = 0;
//                                    for (int j = 1; j < conde.length; j++) {
//                                        if (!conde[j].isEmpty()) {
//                                            debean(titleId, i, conde[j], conde[0], true);
//                                            i++;
//                                        } else {
//                                            continue;
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                        loadData(0, schID + "");
//                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
//                        UpLoadData();
//
//                    }
                    Intent intent = new Intent(context, RecommendActivity.class);
                    startActivityForResult(intent, 100);
                    dialog.dismiss();
                    break;
                case R.id.daoqiri:
                    initRiliDiaLog(daoqiri, null, false);
                    dialog.dismiss();
                    break;
                case R.id.zidingyi_tv:
                    Intent tagintent = new Intent(context, UpdataTagService.class);
                    tagintent.setAction("UpdataTagService");
                    tagintent.putExtra("down", "downtag");
                    tagintent.setPackage(context.getPackageName());
                    context.startService(tagintent);
                    startActivityForResult(new Intent(getActivity(), TagSerachActivity.class), 100);
                    dialog.dismiss();
                    break;
                case R.id.changyong_tv:
                    ReminderDialog reminderDialog = new ReminderDialog(context, R.style.dialog_translucent, getActivity().getWindowManager());
                    reminderDialog.show();
                    reminderDialog.setCallBack(new ReminderDialog.CallBack() {
                        @Override
                        public void reminderTime(int schId) {
                            loadData(0, schId + "");
                        }
                    });
                    dialog.dismiss();
                    break;
            }
        }

        Animation mAnimation = null;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            checkPhonePermission();
            if (autoFag) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    yuyin.setBackground(getActivity().getResources().getDrawable(R.mipmap.btn_huatong_lv));
                    mAnimation = AnimationUtils.loadAnimation(context, R.anim.new_add_yuyin);
                    yuyin.startAnimation(mAnimation);
                    if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                        xunfeiRecognizer();
                    } else {
                        alertFailDialog();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    yuyin.setBackground(getActivity().getResources().getDrawable(R.mipmap.btn_huatong_hui));
                    yuyin.clearAnimation();
                    mIat.stopListening();
                    dialog.dismiss();
                }
            } else {
                Toast.makeText(context, "权限已禁止访问!", Toast.LENGTH_LONG).show();
            }
            return true;
        }
    }


    private void dialogDaoqili(final String date) {
        Today = "";
        final Context context = getActivity();
        final BaseDialog dialog = new BaseDialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View view = fac.inflate(R.layout.activity_adddaoqiriactivity, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(view);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth() - 30;

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        dialog.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        TextView time = (TextView) view.findViewById(R.id.time);
        final EditText addeverytask_tv = (EditText) view.findViewById(R.id.addeverytask_tv);
        view.findViewById(R.id.copy).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                if (clipboardManager.getText() != null) {
                    addeverytask_tv.setText(addeverytask_tv.getText().toString() + clipboardManager.getText().toString());
                    addeverytask_tv.setSelection(addeverytask_tv.getText().toString().length());
                }
            }
        });
        view.findViewById(R.id.save).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!addeverytask_tv.getText().toString().isEmpty()) {
                    try {
                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                        int dqr = Integer.valueOf(sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.DQRBEFORETIME, "4320"));
                        Calendar calender = Calendar.getInstance();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        calender.setTime(simpleDateFormat.parse(date.substring(1, 11)));
                        calender.add(Calendar.DAY_OF_MONTH, -(dqr / 60 / 24));
                        Date date1 = calender.getTime();
                        String ndate = DateUtil.formatDateTimeSs(date1);
                        //计算时间小于今天
                        if (date1.before(DateUtil.parseDate(DateUtil.formatDate(new Date())))) {
                            ndate = DateUtil.formatDate(new Date());
                        }
                        App.getDBcApplication().insertScheduleData(addeverytask_tv.getText().toString() + " (到期日 " + date.substring(1, 11) + ")"
                                , ndate.substring(0, 10), DateUtil.formatDateTimeHm(new Date()), 1,
                                0, 1, 1, 0,
                                0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                "", "", 0, "", DateUtil.formatDateTime(new Date()),
                                1, 0, 0, "到点提醒", "g_001", "", 0, 0, 0, "",
                                "", 0, 0, -1, 0, "", "0", "0");
                        Toast.makeText(context, "创建成功,", Toast.LENGTH_LONG).show();
                        loadData(0, schID + "");
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                        UpLoadData();

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        getActivity().sendBroadcast(intentappwidget);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dialog.dismiss();
                } else {
                    Toast.makeText(context, "内容不能为空", Toast.LENGTH_SHORT).show();
                }

            }
        });
        dialog.setCallBack(new BaseDialog.CallBack() {
            @Override
            public void onTouchOutside() {
                if (!addeverytask_tv.getText().toString().isEmpty()) {
                    try {
                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                        int dqr = Integer.valueOf(sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.DQRBEFORETIME, "4320"));
                        Calendar calender = Calendar.getInstance();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        calender.setTime(simpleDateFormat.parse(date.substring(1, 11)));
                        calender.add(Calendar.DAY_OF_MONTH, -(dqr / 60 / 24));
                        Date date1 = calender.getTime();
                        String ndate = DateUtil.formatDateTimeSs(date1);
                        //计算时间小于今天
                        if (date1.before(DateUtil.parseDate(DateUtil.formatDate(new Date())))) {
                            ndate = DateUtil.formatDate(new Date());
                        }
                        App.getDBcApplication().insertScheduleData(addeverytask_tv.getText().toString() + " (到期日 " + date.substring(1, 11) + ")",
                                ndate.substring(0, 10),
                                DateUtil.formatDateTimeHm(new Date()), 1,
                                0, 1, 1, 0,
                                0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                "", "", 0, "", DateUtil.formatDateTime(new Date()),
                                1, 0, 0, "到点提醒", "g_001", "", 0, 0, 0, "",
                                "", 0, 0, -1, 0, "", "0", "0");
                        loadData(0, schID + "");
                        QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                        UpLoadData();

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        getActivity().sendBroadcast(intentappwidget);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }
        });

        time.setText("到期日: " + date.substring(1, 11));

        imm.showSoftInput(addeverytask_tv, 0);

        dialog.show();

    }

    private void alertClipIsEmptry() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        delete_tv.setText("粘贴内容不能为空！");
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == EasyPermissions.SETTINGS_REQ_CODE) {
            boolean hasReadSmsPermission = EasyPermissions.hasPermissions(getContext(), Manifest.permission.RECORD_AUDIO);
            autoFag = hasReadSmsPermission;
        } else {
            DownFrendCalenderLy();
        }
//        if (sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.WEBEND, "0").equals("1")) {
//            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.WEBEND, "0");
//            loadData(3, "");
//        } else {
//            loadData(4, "");
//        }
        loadData(3, "");
    }


    int position = -1;

    public void updataList() {
        if (!sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, "0.0").equals("0.0")) {
            Map<String, String> map = null;

            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).get(ScheduleTable.schID).equals(sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE,
                        ShareFile.SCHID, "0.0"))) {
                    map = mList.get(i);
                    position = i;
                    break;
                }
            }
            if (map != null) {
                adapter.notifyDataSetChanged();
            }
            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, "0.0");
        }
    }


    /**
     * 下拉刷新
     */
    public void onRefreshs() {
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APPWIDGETUPLOADTYPE, "0");
            sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ENDUPDATETIME, DateUtil.formatDateTimeSs(new Date()));
            pageIndex = 1;
            int noEndCount = App.getDBcApplication().QueryNowGuoQiWeiJieShuCount();// Integer.parseInt(mainMap.get("noEndCount"));
            EventBus.getDefault().post(new PostSendMainActivity(1, noEndCount));

            if (schIDList != null && schIDList.size() > 0) {
                schIDList.clear();
            }
            isNetWork();
            DownFrendCalenderLy();
        }
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();

        if (isShow) {

//            String localpath = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
//            if ("0".equals(localpath)) {
////                freshLayout_header.setTextColor(Color.WHITE);
//                classicsHeader.setAccentColor(Color.WHITE);
//            } else {
////                freshLayout_header.setTextColor(Color.BLACK);
//                classicsHeader.setAccentColor(Color.BLACK);
//            }
            if (sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.IS_MONTH_RE, "1").equals("1")) {
                try {
                    loaddata();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                String image_head = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "");
                String imageUrl = URLConstants.图片 + image_head + "&imageType=2&imageSizeType=3";
                String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
                File outfile = new File(dicr, "TimeApp");
                // 如果文件不存在，则创建一个新文件
                if (!outfile.isDirectory()) {
                    try {
                        outfile.mkdir();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                Bitmap bitmapHead = BitmapFactory.decodeFile(outfile + "/" + image_head.replace('/', '0'));
                if (bitmapHead == null) {
                    imageLoader.displayImage(imageUrl, image_img, options, animateFirstListener);
                    Intent intent = new Intent(context, DownImageService.class);
                    intent.setAction("downimage");
                    intent.putExtra("url", imageUrl);
                    intent.putExtra("name", image_head.replace('/', '0'));
                    context.startService(intent);
                } else {
                    image_img.setImageBitmap(bitmapHead);
                }

                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    DownFrendCalenderLy();
                }
                time = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ALLTIME, "23:59");
                ringdesc = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MUSICDESC, "完成任务");
                ringcode = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MUSICCODE, "g_88");

                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.APP_VERSION, "").equals(getVersion())) {
                    loadData(3, "");
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APP_VERSION, getVersion());
                } else {
                    if (!DateUtil.formatDate(new Date()).equals(
                            sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date())))) {
                        loadData(3, "");
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.IS_MONTH_RE, "1");
                    } else {
                        if (sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.SCHTYPE, "0").equals("1")) {
                            loadData(4, "");
                            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SCHTYPE, "0");
                        }
                    }
                }

                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.YOUKETOUSER, "0").equals("1")) {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.YOUKETOUSER, "0");
                }

                loadData(3, "");
            }
        }
    }

    public static String Today() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    public static String Week() {
        String week = "星期日";
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        switch (weekday) {
            case 1:
                week = "星期日";
                break;
            case 2:
                week = "星期一";
                break;
            case 3:
                week = "星期二";
                break;
            case 4:
                week = "星期三";
                break;
            case 5:
                week = "星期四";
                break;
            case 6:
                week = "星期五";
                break;
            case 7:
                week = "星期六";
                break;
        }

        return week;
    }


    static Bitmap drawableToBitmap(Drawable drawable) // drawable 转换成 bitmap
    {
        int width = drawable.getIntrinsicWidth(); // 取 drawable 的长宽
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565; // 取 drawable 的颜色格式
        Bitmap bitmap = Bitmap.createBitmap(width, height, config); // 建立对应
        // bitmap
        Canvas canvas = new Canvas(bitmap); // 建立对应 bitmap 的画布
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas); // 把 drawable 内容画到画布中
        return bitmap;
    }

    /**
     * 登录广播接收器
     */
    private UpdateDataReceiver receiver = null;
    private NoticeOnRefresh noticeOnRefresh = null;
    NoticeOnRefresh2 noticeOnRefresh2;

    @Override
    public void onDestroy() {
        if (receiver != null) {
            getActivity().unregisterReceiver(receiver);
        }

        if (noticeOnRefresh != null) {

            localBroadcastManager.unregisterReceiver(noticeOnRefresh);
        }
        if (noticeOnRefresh2 != null) {

            localBroadcastManager.unregisterReceiver(noticeOnRefresh2);
        }

        isCreate = false;
        // 退出时释放连接
        mIat.cancel();
        mIat.destroy();
        EventBus.getDefault().unregister(this);
//        App.getHttpQueues().cancelAll("down");
//        App.getHttpQueues().cancelAll("upload");
//        App.getHttpQueues().cancelAll("download");
        handler.removeCallbacksAndMessages(null);
        handler1.removeCallbacksAndMessages(null);
        if (schIDList != null && schIDList.size() > 0) {
            schIDList.clear();
        }
        if (ntype != null) {
            getActivity().unregisterReceiver(ntype);
        }
        if (appwidget != null) {
            getActivity().unregisterReceiver(appwidget);
        }
        super.onDestroy();
    }

    private void showSM() {
        if ("0".equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISSHOWDIALOG, "0"))) {
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISSHOWDIALOG, "1");

            dialog = new DialogWidget(getActivity(),
                    new DialogBarView(getActivity(), R.layout.new_first_dialog_tishi, this).getView(),
                    R.style.MyDialogs);
            dialog.show();
        }
    }


    LocalBroadcastManager localBroadcastManager;

    public class NoticeOnRefresh extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            loadData(3, "");
        }
    }

    public class NoticeOnRefresh2 extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            month_layout.setVisibility(View.GONE);
            sch_layout.setVisibility(View.VISIBLE);
        }
    }

    public class UpdateDataReceiver extends BroadcastReceiver {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(Context context, Intent intent) {
            firstlogin = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
            if ("dismiss".equals(intent.getAction())) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    if ("0".equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0"))) {
                        LoginDownServiceDialog loginDownServiceDialog = new LoginDownServiceDialog(
                                context, R.style.dialog_translucent, getActivity().getWindowManager());
                        loginDownServiceDialog.show();
                    }
                }
            } else {
                String firststate = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "1");
                // 做一些修改界面之类的工作
                String result = intent.getStringExtra("data");
                int index = intent.getIntExtra("index", 0);
                int what = intent.getIntExtra("what", 0);
                isLoginService = intent.getBooleanExtra("isLoginService", false);
                if ("0".equals(firststate)) {
                    what = 1;
                }
                System.err.println("what的数字：" + what);
                refreshLayout.finishRefresh();

                if (result.equals("success")) {
                    Message message = Message.obtain();
                    message.obj = index;
                    message.what = what;
                    handler1.sendMessage(message);
                } else {
                    Message message = Message.obtain();
                    message.obj = "fail";
                    message.what = -2;
                    handler1.sendMessage(message);
                }
            }
        }
    }

    boolean isLoginService = false;
    private Handler handler1 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg == null) {
                return;
            }

            // int str = (Integer) msg.obj;
            switch (msg.what) {
                case -2:
                    loadCount();
                    adapter.notifyDataSetChanged();
                    break;
                case 1:
                    MainActivity.instance.CheckCreateRepeatSchData();
                    //关闭第一次dialog
                    if (isLoginService) {
                        Intent LoginDownDataReceiver = new Intent("LoginDownDataReceiver");
                        LoginDownDataReceiver.putExtra("setData", "setData");
                        getActivity().sendBroadcast(LoginDownDataReceiver);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                showSM();
                            }
                        }, 6000);
                    } else {
                        if (sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.DELETETYPE, "0").equals("1")) {
                            loadData(3, "");
                            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DELETETYPE, "0");
                        } else {
                            loadData(3, "");
                        }
                    }
                    break;
                case 2:
                    loadData(3, "");
                    break;
                case 0:
                    if (isLoginService) {
                        Intent LoginDownDataReceiver = new Intent("LoginDownDataReceiver");
                        LoginDownDataReceiver.putExtra("setData", "setData");
                        getActivity().sendBroadcast(LoginDownDataReceiver);
                    }
                    loadCount();
                    adapter.notifyDataSetChanged();
                    break;
            }
        }

    };

    /**
     * 点击头部，弹出以前，重要，重要未结束，取消布局
     */
    /**
     * 普通记事点击弹出详情菜单 setType 0,菜单详情 1,设置
     */
    private void alterImportantDialog() {
        Context context = getActivity();
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
//        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_importantandold, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        new alterImportantDialogOnClick(dialog, more_pop_menu);
    }

    class alterImportantDialogOnClick implements OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView old_tv;
        private TextView important_tv, daiban_tv, daoqiri_tv;
        private TextView come_friends_tv;
        // private TextView fenxiangsch_tv;// 分享日程
        private TextView sousuo_tv;
        private TextView canel_tv;
        private TextView newinformation_tv;

        @SuppressLint("NewApi")
        public alterImportantDialogOnClick(Dialog dialog, View view) {
            this.dialog = dialog;
            this.view = view;
            initview();
        }

        private void initview() {
            old_tv = (TextView) view.findViewById(R.id.old_tv);
            old_tv.setOnClickListener(this);
            important_tv = (TextView) view.findViewById(R.id.important_tv);
            important_tv.setOnClickListener(this);
            come_friends_tv = (TextView) view
                    .findViewById(R.id.come_friends_tv);
            come_friends_tv.setOnClickListener(this);
            // fenxiangsch_tv = (TextView)
            // view.findViewById(R.id.fenxiangsch_tv);
            // fenxiangsch_tv.setOnClickListener(this);
            sousuo_tv = (TextView) view.findViewById(R.id.sousuo_tv);
            sousuo_tv.setOnClickListener(this);
            canel_tv = (TextView) view.findViewById(R.id.canel_tv);
            canel_tv.setOnClickListener(this);
            newinformation_tv = (TextView) view.findViewById(R.id.newinformation_tv);
            newinformation_tv.setOnClickListener(this);
            daiban_tv = (TextView) view.findViewById(R.id.daiban_tv);
            daiban_tv.setOnClickListener(this);
            daoqiri_tv = (TextView) view.findViewById(R.id.daoqiri_tv);
            daoqiri_tv.setOnClickListener(this);

            view.findViewById(R.id.set_tv).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent x = new Intent(context, WebViewActivity.class);
                    x.putExtra("url", "http://www.keytimeapp.com/setup.html");
                    x.putExtra("remark2", "不提醒的解决办法");
                    startActivity(x);
                }
            });

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.old_tv:
                    startActivityForResult(new Intent(getActivity(),
                            YiQianActivity.class), 100);
                    dialog.dismiss();
                    break;
                case R.id.important_tv:
                    startActivityForResult(new Intent(getActivity(),
                            ImportantSchActivity.class), 100);
                    dialog.dismiss();
                    break;
                case R.id.come_friends_tv:
                    startActivityForResult(new Intent(getActivity(),
                            ComeFriendSchActivity.class), 100);
                    dialog.dismiss();
                    break;
                case R.id.sousuo_tv:
                    Intent tagintent = new Intent(context, UpdataTagService.class);
                    tagintent.setAction("UpdataTagService");
                    tagintent.putExtra("down", "downtag");
                    tagintent.setPackage(context.getPackageName());
                    context.startService(tagintent);
                    startActivityForResult(new Intent(getActivity(),
                            TagSerachActivity.class), 100);
                    dialog.dismiss();
                    break;
                case R.id.canel_tv:
                    dialog.dismiss();
                    break;
                case R.id.newinformation_tv:
                    Intent newif = new Intent(getActivity(),
                            NewInformationActivity.class);
                    newif.putExtra("type", 0);
                    startActivityForResult(newif, 100);
                    dialog.dismiss();
                    break;
                case R.id.daiban_tv:
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE,
                            ShareFile.ISNEWYOUKE, "0").equals("0")) {
                        Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                        newt.putExtra("type", 1);
                        newt.putExtra("login", true);
                        startActivity(newt);
                    } else {
                        Intent intentn = new Intent(context,
                                NewMyActivity.class);
                        startActivityForResult(intentn, 100);
                    }
                    dialog.dismiss();
                    break;
                case R.id.daoqiri_tv:
                    startActivityForResult(new Intent(getActivity(),
                            RepeatDaoQiDateActivity.class), 100);
                    dialog.dismiss();
                    break;
            }
        }
    }

    private void setNewsImg() {
//        int count = application.QueryNewNoteRedHeadCount();
//        if (count > 0) {
//            news_img.setVisibility(View.VISIBLE);
//        } else {
//            news_img.setVisibility(View.GONE);
//        }
    }

    private void loadCount() {
        MainActivity.instance.loadCount();
        setNewsImg();
    }


    /**
     * 讯飞语音
     */
    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d("TAG", "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(context, "初始化失败，错误码：" + code, Toast.LENGTH_LONG)
                        .show();
            }
        }
    };
    String mycontent = "";

    private void xunfeiRecognizer() {
        int ret = 0; // 函数调用返回值
        // 设置参数
        setParam();
        boolean isShowDialog = mSharedPreferences.getBoolean("iat_show", false);
        if (isShowDialog) {
            // 显示听写对话框
            mIatDialog.setListener(mRecognizerDialogListener);
            mIatDialog.show();
            Toast.makeText(context, "请开始说话…", Toast.LENGTH_SHORT).show();
        } else {
            // 不显示听写对话框
            ret = mIat.startListening(mRecognizerListener);
            if (ret != ErrorCode.SUCCESS) {
                // showTip("听写失败,错误码：" + ret);
            } else {
                // showTip(getString(R.string.text_begin));
                // Toast.makeText(context, "请开始说话…", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results);
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
            // showTip(error.getPlainDescription(true));
            // Toast.makeText(context, error.getPlainDescription(true),
            // Toast.LENGTH_SHORT).show();
        }

    };
    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            // Toast.makeText(context, "开始说话", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
            // Toast.makeText(context, error.getPlainDescription(true),
            // Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            // Toast.makeText(context, "结束说话", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d("TAG", results.getResultString());
            printResult(results);

            if (isLast) {
                StringBuffer resultBuffer = new StringBuffer();
                for (String key : mIatResults.keySet()) {
                    resultBuffer.append(mIatResults.get(key));
                }
                mycontent = resultBuffer.toString();
                mIatResults.clear();
                System.out.println("=================>>" + mycontent);
                if (!"".equals(mycontent)) {
                    Map<Object, Object> map = ReadWeiXinXml.yuyinSb(context, mycontent);
                    int displaytime, postpone;
                    Calendar calendar = Calendar.getInstance();
                    if (map != null) {
                        if ("0".equals(map.get("di")) && "0".equals(map.get("ti"))) {
                            displaytime = 0;
                            postpone = 1;
                        } else {
                            displaytime = 1;
                            postpone = 0;
                        }
                        String alamsound = (String) map.get("ringDesc");
                        String alamsoundDesc = (String) map.get("ringVal");
                        String content = (String) map.get("value");

                        calendar.setTime(new Date());
                        today = DateUtil.formatDate(calendar.getTime());
                        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);

                        String date = DateUtil.formatDate(DateUtil.parseDate((String) map.get("date")));

                        try {
                            String before = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
                            final int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.SCHID, schID + "");
                            YuyinDetailDialog detailDialog = new YuyinDetailDialog(context, R.style.dialog_translucent,
                                    getActivity().getWindowManager(), date, (String) map.get("time"), content, displaytime, postpone,
                                    before, alamsoundDesc, alamsound);
                            detailDialog.show();
                            detailDialog.setCallBack(new YuyinDetailDialog.CallBack() {
                                @Override
                                public void abcdefg() {
                                    loadData(0, schID + "");
                                    QueryAlarmData.writeAlarm(getActivity().getApplicationContext());
                                    UpLoadData();

                                    Intent intertwined = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                                    Bundle extras = new Bundle();
                                    intertwined.putExtras(extras);
                                    getActivity().sendBroadcast(intertwined);
                                }
                            });
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    Toast.makeText(context, "请说话…", Toast.LENGTH_SHORT).show();
                }
                mycontent = "";
            }
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            // Toast.makeText(context, "当前正在说话，音量大小：" + volume,
            // Toast.LENGTH_SHORT)
            // .show();
            Log.d("TAG", "返回音频数据：" + data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            // if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            // Log.d(TAG, "session id =" + sid);
            // }
        }

    };

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);
    }

    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        String lag = mSharedPreferences.getString("iat_language_preference",
                "mandarin");
        if (lag.equals("en_us")) {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        } else {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        }

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS,
                mSharedPreferences.getString("iat_vadbos_preference", "10000"));

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS,
                mSharedPreferences.getString("iat_vadeos_preference", "2000"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT,
                mSharedPreferences.getString("iat_punc_preference", "1"));

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                Environment.getExternalStorageDirectory() + "/msc/iat.wav");

        // 设置听写结果是否结果动态修正，为“1”则在听写过程中动态递增地返回结果，否则只在听写结束之后返回最终结果
        // 注：该参数暂时只对在线听写有效
        mIat.setParameter(SpeechConstant.ASR_DWA,
                mSharedPreferences.getString("iat_dwa_preference", "0"));
    }

    private void sendMessageDialog(String content) {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.y = 150;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_sendmessagedialog,
                null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getActivity().getWindowManager().getDefaultDisplay()
                .getWidth() - 30;
        dialog.show();
        new SendMessageDetailOnClick(dialog, more_pop_menu, content);
    }

    class SendMessageDetailOnClick implements OnClickListener {

        private View mainView;
        private Dialog dialog;
        private String content;
        private String alamsound;
        private String alamsoundDesc;
        private LinearLayout detail_edit;
        private LinearLayout detail_close;
        private Button suresend_bt;
        private TextView time_date;
        private TextView year_date;
        private TextView shunyan_tv;
        private TextView content_tv;
        private TextView timebefore_tv;
        private TextView week_date;
        Map<Object, Object> map;
        String today, tomorrow;
        Calendar calendar = Calendar.getInstance();
        int displaytime, postpone;
        String date;

        public SendMessageDetailOnClick(Dialog dialog, View view, String content) {
            this.mainView = view;
            this.dialog = dialog;
            this.content = content;
            initview();
            initdata();
        }

        public void initview() {
            detail_edit = (LinearLayout) mainView
                    .findViewById(R.id.detail_edit);
            detail_edit.setOnClickListener(this);
            detail_close = (LinearLayout) mainView
                    .findViewById(R.id.detail_close);
            detail_close.setOnClickListener(this);
            suresend_bt = (Button) mainView.findViewById(R.id.suresend_bt);
            suresend_bt.setOnClickListener(this);
            time_date = (TextView) mainView.findViewById(R.id.time_date);
            year_date = (TextView) mainView.findViewById(R.id.year_date);
            shunyan_tv = (TextView) mainView.findViewById(R.id.shunyan_tv);
            content_tv = (TextView) mainView.findViewById(R.id.content_tv);
            timebefore_tv = (TextView) mainView
                    .findViewById(R.id.timebefore_tv);
            week_date = (TextView) mainView.findViewById(R.id.week_date);
            map = ReadWeiXinXml.yuyinSb(context, content);
        }

        public void initdata() {
            if (map != null) {
                if ("0".equals(map.get("di")) && "0".equals(map.get("ti"))) {
                    displaytime = 0;
                    postpone = 1;
                } else {
                    displaytime = 1;
                    postpone = 0;
                }
                alamsound = (String) map.get("ringDesc");
                alamsoundDesc = (String) map.get("ringVal");
                content = (String) map.get("value");

                calendar.setTime(new Date());
                today = DateUtil.formatDate(calendar.getTime());
                calendar.set(Calendar.DAY_OF_MONTH,
                        calendar.get(Calendar.DAY_OF_MONTH) + 1);
                tomorrow = DateUtil.formatDate(calendar.getTime());

                content_tv.setText(content);
                date = DateUtil.formatDate(DateUtil.parseDate((String) map
                        .get("date")));
                if (today.equals(date)) {
                    year_date.setText(date);
                } else if (tomorrow.equals(date)) {
                    year_date.setText("明天");
                } else {
                    year_date.setText(date);
                }
                String timestr = "";
                if (displaytime == 0) {
                    time_date.setText("全天");
                    timestr = sharedPrefUtil.getString(context,
                            ShareFile.USERFILE, ShareFile.ALLTIME, "23:59");
                } else {
                    time_date.setText((String) map.get("time"));
                    timestr = time_date.getText().toString();
                }
                week_date.setText(CharacterUtil.getWeekOfDate(context,
                        DateUtil.parseDate(date)));
                String colorState = ""
                        + context.getResources().getColor(
                        R.color.mingtian_color);
                String sequence = "<font color='" + colorState + "'>"
                        + context.getString(R.string.adapter_shun) + "</font>";

                shunyan_tv.setBackgroundResource(R.drawable.tv_kuang_aftertime);
                shunyan_tv.setText(Html.fromHtml(sequence));
                if (0 == postpone) {
                    shunyan_tv.setVisibility(View.GONE);
                } else {
                    shunyan_tv.setVisibility(View.VISIBLE);
                }
                Date dateStr = DateUtil.parseDateTime(date + " " + timestr);
                Date dateToday = DateUtil.parseDateTime(DateUtil
                        .formatDateTime(new Date()));
                long betweem = (long) (dateStr.getTime() - dateToday.getTime()) / 1000;
                long day = betweem / (24 * 3600);
                long hour = betweem % (24 * 3600) / 3600;
                long min = betweem % 3600 / 60;

                if (today.equals(date)) {// 今天
                    if (displaytime == 0 && postpone == 1) {
                        timebefore_tv.setText("今天");
                    } else {
                        if (DateUtil.parseDate(DateUtil.formatDate(new Date())).after(DateUtil.parseDate(DateUtil.formatDate(dateStr)))) {
                            if (Math.abs(hour) >= 1) {
                                timebefore_tv.setText(Math.abs(hour) + "小时前");
                            } else {
                                timebefore_tv.setText(Math.abs(min) + "分钟前");
                            }
                        } else {
                            if (Math.abs(hour) >= 1) {
                                timebefore_tv.setText(Math.abs(hour) + "小时后");
                            } else {
                                timebefore_tv.setText(Math.abs(min) + "分钟后");
                            }
                        }
                    }
                } else if (tomorrow.equals(date)) {// 明天
                    if (Math.abs(day) >= 1) {
                        timebefore_tv.setText(Math.abs(day) + "天后");
                    } else {
                        timebefore_tv.setText(Math.abs(hour) + "小时后");
                    }
                } else {
                    timebefore_tv.setText(Math.abs(day) + 1 + "天后");
                }
            }
        }

        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (v.getId()) {
                case R.id.detail_edit:
                    if (!"".equals(content_tv.getText().toString().trim())) {
                        intent = new Intent(context, EditSchActivity.class);
                        intent.putExtra("content", content);
                        intent.putExtra("displaytime", displaytime + "");
                        intent.putExtra("postpone", postpone + "");
                        intent.putExtra("ringdesc", alamsoundDesc);
                        intent.putExtra("ringcode", alamsound);
                        intent.putExtra("date", date);
                        intent.putExtra("time", (String) map.get("time"));
                        startActivityForResult(intent, 100);
                        dialog.dismiss();
                    } else {
                        Toast.makeText(context, "提醒内容不能为空..", Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                    break;
                case R.id.detail_close:
                    dialog.dismiss();
                    break;
                case R.id.suresend_bt:
                    try {
                        String before = sharedPrefUtil.getString(context,
                                ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
                        int schID = App.getDBcApplication().getLocalId(-1, "ScheduleTable", ScheduleTable.schID);
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE,
                                ShareFile.SCHID, schID + "");
                        App.getDBcApplication().insertScheduleData(content, date,
                                (String) map.get("time"), 1,
                                Integer.parseInt(before), displaytime, postpone, 0,
                                0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                "", "", 0, "", DateUtil.formatDateTime(new Date()),
                                1, 0, 0, alamsoundDesc, alamsound, "", 0, 0, 0, "",
                                "", 0, 0, 0, 0, "", "0", "0");
                        loadData(0, schID + "");
                        QueryAlarmData.writeAlarm(getActivity()
                                .getApplicationContext());
                        UpLoadData();

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        getActivity().sendBroadcast(intentappwidget);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    dialog.dismiss();
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 话筒对话框
     */
    Dialog huatongdialog = null;
    Button yuyin;


    private void alertFailDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        delete_tv.setText("请检查您的网络！");
        delete_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }

    public void onEventMainThread(FristFragment event) {

        String msg = event.getMsg();
        if ("0".equals(msg) && isShow) {
            // MainActivity.CheckCreateRepeatSchData();
//            loadCount();
//            loadData(3, "");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (vibrator != null) {
            vibrator.cancel();
        }
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        // 填充各控件的数据
    }

    @SuppressLint("NewApi")
    @Override
    public void callbackUpdateDialog(int type) {
        if (type == 110) {
            dialog.dismiss();
        } else if (type == 120) {
            Intent tohelp = new Intent(getActivity(), HelpActivity.class);
            startActivity(tohelp);
            dialog.dismiss();
        }
    }

    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    private void checkPhonePermission() {
        if (Build.VERSION.SDK_INT < 23) {
            autoFag = true;
        } else {
            String[] perms = {Manifest.permission.RECORD_AUDIO};
            if (EasyPermissions.hasPermissions(getActivity(), perms)) {
                // Have permissions, do the thing!
                autoFag = true;
            } else {
                // Ask for both permissions
                EasyPermissions.requestPermissions(this, "该应用需要这些权限，为了保证应用正常运行!",
                        RC_LOCATION_CONTACTS_PERM, perms);
            }
            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.PERMISSIONSTATE, "1");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        if (PackageManager.PERMISSION_GRANTED == grantResults[3]) {
            autoFag = true;
        } else {
            autoFag = false;
        }
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d("TAG", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
                getString(R.string.rationale_ask_again),
                R.string.action_settings, R.string.cancel, null, perms);
    }


    private List<LyNewNumBean.ListBean> listBeanList;

    /**
     * 查询留言更新数量
     */
    public void DownFrendCalenderLy() {

        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST + "/appFrends_findLyNewNum.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                LyNewNumBean lyNewNum = gson.fromJson(result, LyNewNumBean.class);
                                listBeanList.clear();
                                if (lyNewNum.status == 0) {
                                    listBeanList = lyNewNum.list;
                                    adapter.setNewState(listBeanList);
                                } else {
                                    adapter.setNewState(listBeanList);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userid);
                map.put("type", "1");
                return map;
            }
        };
        stringRequest.setTag("findLyNewNum");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    /**
     * app日程同步下行修改好友信息和留言
     */
    public void updateFrendsPostState(final String cid) {

        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST + "/appFrends_updateFrendsPostState.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                if (responseCode(result)) {
                                    //TODO  同步成功
                                } else {
//                                    updateFrendsPostState(cid);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userid);
                map.put("cId", cid);
                return map;
            }
        };
        stringRequest.setTag("findLyNewNum");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    public boolean responseCode(String response) throws JSONException {
        int status = 0;
        JSONObject jsonObject = new JSONObject(response);
        int msg = jsonObject.getInt("status");
        return status == msg;
    }

    class newtype extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Integer.valueOf(intent.getExtras().get("l").toString()) == 1) {
                loadData(3, "");
                DownFrendCalenderLy();
            }
        }
    }


    class appwidget extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getExtras().getBoolean("aappwidget", false) == true) {
                onRefreshs();
            }
            if (intent.getExtras().getBoolean("aappwidget1", false) == true) {
                loadData(3, "");
            }
        }
    }

    public String getVersion() {
        try {
            PackageManager manager = getActivity().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            String version = info.versionName;
            return "V" + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "V6.3.2";
        }
    }


    private TextView mTitle, month_tv_right, year_tv_right;
    private LinearLayout date_ll, top_ll_right_m, top_ll_left_m;
    ImageView ll_back;

    private void loadMonthView() {
        calenderView = view.findViewById(R.id.calenderView);
        calenderView.setOnItemClickListener(this);
        mTitle = view.findViewById(R.id.mTitle);
        month_tv_right = view.findViewById(R.id.month_tv);
        year_tv_right = view.findViewById(R.id.year_tv);
        top_ll_right_m = view.findViewById(R.id.top_ll_right_m);
        top_ll_left_m = view.findViewById(R.id.top_ll_left_m);
        date_ll = view.findViewById(R.id.date_ll);
        ll_back = view.findViewById(R.id.ll_back);
        calenders = App.getDBcApplication().queryNOTHOLIDAYs();
        today = DateUtil.formatDate(new Date());
        int[] dateArr = CalendarUtil.getYMD(new Date());
        standard_year = dateArr[0];
        standard_month = dateArr[1];
        calenderView.setAdapter(calenderadapter);
        calenderView.setHandler(calenderhandler);
        synchronized (getActivity()) {
            calenderView.setData(getMonthOfDayList(dateArr[0], dateArr[1]), true);
        }

        month_tv_right.setText(DateUtil.nowMonth());
        year_tv_right.setText("月/" + DateUtil.nowYear());

        top_ll_left_m.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                ValueAnimator fadeAnim = ObjectAnimator.ofFloat(month_layout, "translationY", 0f, -ScreenUtils.getScreenHeight(context));
                fadeAnim.setDuration(200);
                fadeAnim.start();
                Intent intent = new Intent("noticeOnRefresh1");
                intent.putExtra("isMonth", false);
                localBroadcastManager.sendBroadcast(intent);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        month_layout.setVisibility(View.GONE);
                    }
                }, 200);

            }
        });

        top_ll_right_m.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int[] dateArr = CalendarUtil.getYMD(new Date());
                standard_year = dateArr[0];
                standard_month = dateArr[1];
                month_tv_right.setText(DateUtil.nowMonth());
                year_tv_right.setText("月/" + DateUtil.nowYear());
                calenderView.setData(getMonthOfDayList(dateArr[0], dateArr[1]), true);
                return true;
            }
        });


        mTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CalenderTopCenterDialog dialog = new CalenderTopCenterDialog(getActivity(), R.style.dialog_translucent_top, getActivity().getWindowManager());
                dialog.show();
                dialog.setCallBack(new CalenderTopCenterDialog.CallBack() {
                    @Override
                    public void setType(int index, String title) {
                        if (index == 0) {
                            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
                        } else {
                            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.LOCALPATH, "0");
                        }
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.TYPEINDEX, index + "");
                        sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.TYPETITLE, title);
                        MainActivity.instance.setmainbg();
                        try {
                            loaddata();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        Intent intent = new Intent("noticeOnRefresh");
                        localBroadcastManager.sendBroadcast(intent);
                    }
                });
            }
        });

    }


    List<Map<String, String>> calenders = new ArrayList<>();
    ArrayList<Map<String, String>> dblists = new ArrayList<>();
    ArrayList<Map<String, String>> ulists = new ArrayList<>();
    List<Map<String, String>> queryAllChongFuData = new ArrayList<>();


    int colorss[] = {R.color.white, R.color.color_m_1, R.color.color_m_2, R.color.color_m_3, R.color.color_m_4, R.color.color_m_5};
    CaledarAdapter calenderadapter = new CaledarAdapter() {
        @Override
        public View getView(View convertView, ViewGroup parentView, final CalendarBean bean) {
            //判断convertView为null，可以有效利用view的回收重用，左右滑动的效率高
            //mothFlag 0是当月，-1是月前，1是月后
            if (convertView == null) {
                convertView = LayoutInflater.from(parentView.getContext()).inflate(R.layout.month_view_fragment_item, null);
            }
            final TextView calender_tv = convertView.findViewById(R.id.calender_tv);
            calender_tv.setText("");
            TextView chinaText = convertView.findViewById(R.id.no);
            chinaText.setText("");
            chinaText.setTextColor(getResources().getColor(R.color.gongkai_txt));
            TextView text = convertView.findViewById(R.id.number);
            text.setText("");
            text.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            text.setTextColor(getResources().getColor(R.color.gongkai_txt));
            RelativeLayout today_ll = convertView.findViewById(R.id.today_ll);
            today_ll.setBackground(getActivity().getResources().getDrawable(R.drawable.calender_white));

            String month = bean.moth + "";
            String day = bean.day + "";

            if (bean.moth < 10) {
                month = "0" + bean.moth;
            }

            if (bean.day < 10) {
                day = "0" + bean.day;
            }

            final String selected_day = bean.year + "-" + month + "-" + day;
            if (bean.mothFlag == 0) {
                text.setText("" + bean.day);
                calender_tv.setTextColor(Color.BLACK);
                String lunar_holiday = "";
                for (Map<String, String> map : calenders) {
                    if (map.get("calender").equals(selected_day)) {
                        lunar_holiday = map.get("LUNAR_HOLIDAY");
                        break;
                    }
                }
                if (lunar_holiday.isEmpty()) {
                    chinaText.setText(bean.chinaDay);
                } else {
                    chinaText.setText(lunar_holiday);
                }

                int numbers = Utils.pxTodip(getActivity(), width / 7 - Utils.dipTopx(getActivity(), 10)) / 9;
                int lines = Utils.pxTodip(getActivity(), heigth - Utils.dipTopx(getActivity(), 120)) / 7 / 9 + 1;

                StringBuilder contents = new StringBuilder();
                List<Map<String, String>> dblist = new ArrayList<>();
                List<Map<String, String>> ulist = new ArrayList<>();
                List<Map<String, String>> list = new ArrayList<>();
                List<Map<String, String>> newlist = new ArrayList<>();
                List<Map<String, String>> newulist = new ArrayList<>();

                for (Map<String, String> map : dblists) {
                    if (map.get(ScheduleTable.schDate).equals(selected_day)) {
                        dblist.add(map);
                    }
                }


                for (Map<String, String> mMap : ulists) {
                    if (mMap.get(ScheduleTable.schDate).equals(selected_day)) {
                        if (!"0".equals(mMap.get(ScheduleTable.schRepeatID)) && !"0".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                            String type = App.getDBcApplication().queryRepateType(mMap.get(ScheduleTable.schRepeatID)).get("type");
                            if (!"1".equals(type) && !"5".equals(type)) {
                                ulist.add(mMap);
                            }
                        } else {
                            ulist.add(mMap);
                        }
                        if (dblist.size() > 0) {
                            if (ulist.size() >= lines - 1) {
                                break;
                            }
                        }
                    }
                }

                newlist.addAll(dblist);
                newlist.addAll(ulist);
                for (Map<String, String> mMap : newlist) {
                    if (!"0".equals(mMap.get(ScheduleTable.schRepeatID)) && !"0".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                        String type = App.getDBcApplication().queryRepateType(mMap.get(ScheduleTable.schRepeatID)).get("type");
                        if (!"1".equals(type) && !"5".equals(type)) {
                            list.add(mMap);
                        }
                    } else {
                        list.add(mMap);
                    }
                }

                List<String> colors = new ArrayList<>();
                if (selected_day.equals(today) && bean.mothFlag == 0) {
                    if (dblist.size() > 0) {
                        contents = new StringBuilder("待办(" + dblist.size() + ")\n");
                        colors.add("0");
                    }
                    for (int i = 0; i < ulist.size(); i++) {
                        Map<String, String> map = ulist.get(i);
                        if (i < lines - 1) {
                            String content = map.get(ScheduleTable.schContent);
                            if (content.length() > numbers) {
                                content = content.substring(0, numbers);
                            }
                            contents.append(content).append("\n");
                            colors.add(map.get(ScheduleTable.schRemark11));
                        }
                    }
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        Map<String, String> map = list.get(i);
                        if (i < lines) {
                            String content = map.get(ScheduleTable.schContent);
                            if (content.length() > numbers) {
                                content = content.substring(0, numbers);
                            }
                            contents.append(content).append("\n");
                            colors.add(map.get(ScheduleTable.schRemark11));
                        }
                    }
                }

                int s_i = 0;
                for (Map<String, String> mMap : queryAllChongFuData) {
                    String content = mMap.get(CLRepeatTable.repContent);
                    if (content.length() > numbers) {
                        content = content.substring(0, numbers);
                    }

                    int cl = contents.toString().isEmpty() ? 0 : contents.toString().split("\n").length;

                    // 每周
                    if (s_i <= lines - cl) {
                        if (mMap.get(CLRepeatTable.repType).equals("2")) {
                            int days = DateUtil.days(mMap.get(CLRepeatTable.repNextCreatedTime), selected_day);
                            if (days > 0 && days % 7 == 0) {
                                contents.append(content).append("\n");
                                colors.add("-1");
                                s_i++;
                            }
                        }
                        if (mMap.get(CLRepeatTable.repType).equals("3")) {
                            int days = DateUtil.days(mMap.get(CLRepeatTable.repNextCreatedTime), selected_day);
                            String repTypeParameter = mMap.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\"", "");
                            if (days > 0 && repTypeParameter.equals(day)) {
                                contents.append(content).append("\n");
                                colors.add("-1");
                                s_i++;
                            }
                        }

                        if (mMap.get(CLRepeatTable.repType).equals("4")) {
                            int days = DateUtil.days(mMap.get(CLRepeatTable.repNextCreatedTime), selected_day);
                            String repTypeParameter = mMap.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\"", "");
                            if (days > 0 && repTypeParameter.equals(month + "-" + day)) {
                                contents.append(content).append("\n");
                                colors.add("-1");
                                s_i++;
                            }
                        }
                    }
                }

                int days = DateUtil.days(selected_day);
                if (days >= 0) {
                    SpannableStringBuilder style = new SpannableStringBuilder(contents.toString());
                    String contentss[] = contents.toString().split("\n");
                    int start = 0;
                    int end = 0;
                    for (int i = 0; i < colors.size(); i++) {
                        if (i == colors.size() - 1) {
                            end += contentss[i].length();
                        } else {
                            end += contentss[i].length() + 1;
                        }
                        String remark11 = colors.get(i) == null ? "0" : colors.get(i);
                        if (remark11.equals("")) {
                            remark11 = "0";
                        }
                        int color = Integer.valueOf(remark11);
                        if (color > 0) {
                            style.setSpan(new BetterHighlightSpan(
                                    getActivity().getResources().getColor(colorss[color]), color > 2 ? Color.WHITE : Color.BLACK
                                    , Utils.dipTopx(getActivity(), 11)), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        } else if (color < 0) {
                            style.setSpan(new ForegroundColorSpan(getActivity().getResources().getColor(R.color.gongkai_txt3)), start, end,
                                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        }
                        start += contentss[i].length() + 1;

                    }
                    calender_tv.setText(style);
                } else {
                    calender_tv.setText(contents.toString());
                    calender_tv.setTextColor(getActivity().getResources().getColor(R.color.gongkai_txt3));
                }
            }


            if (selected_day.equals(today) && bean.mothFlag == 0) {
                text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                text.setTextColor(Color.WHITE);
                chinaText.setTextColor(Color.WHITE);
                today_ll.setBackground(getActivity().getResources().getDrawable(R.drawable.red_round_fill));
            }

            return convertView;
        }
    };


    private void loaddata() {
        try {
            String index = sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
            if (index == null && index.equals("")) {
                index = "0";
            }
            String newtitle = sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.TYPETITLE, "我的日程");
            int newopeartType = Integer.valueOf(index);
            if (newopeartType < 0) {
                mTitle.setText(newtitle);
            } else {
                mTitle.setText("我的日程");
            }
            newopeartTypes = newopeartType;
            ulists.clear();
            dblists.clear();
            queryAllChongFuData.clear();
            switch (newopeartType) {
                case -1://以前
                    ulists.addAll(App.getDBcApplication().queryAllSchData(22, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(23, 0, 0));
                    break;
                case -2:
                    ulists.addAll(App.getDBcApplication().queryAllSchData(25, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(26, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(27, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(28, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(29, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(30, 0, 0));
                    break;
                case -3:
                    ulists.addAll(App.getDBcApplication().queryAllSchData(-6, 0, 0));
                    break;
                case -4:
                    ulists.addAll(App.getDBcApplication().queryAllSchData(66, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(67, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(68, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(69, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(70, 0, 0));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(71, 0, 0));
                    break;
                case -6:
                case -7:
                case -8:
                case -9:
                case -10:
                case -11:
                case -12:
                    newopeartType = Math.abs(newopeartType) - 5;

                    ulists.addAll(App.getDBcApplication().queryAllSchData(50, 0, newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(51, 0, newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(52, 0, newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(53, 0, newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(54, 0, newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(55, 0, newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(50, 0, 100 + newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(51, 0, 100 + newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(52, 0, 100 + newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(53, 0, 100 + newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(54, 0, 100 + newopeartType));
                    ulists.addAll(App.getDBcApplication().queryAllSchData(55, 0, 100 + newopeartType));

                    break;
                default:
                    if (!sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.TYPEUID, "").isEmpty()) {
                        String uid = sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.TYPEUID, "9999991");
                        ulists = App.getDBcApplication().queryCalenderData("", Integer.valueOf(uid));
                    } else {
                        queryAllChongFuData = App.getDBcApplication().QueryAllChongFuData(9);
                        dblists = App.getDBcApplication().queryCalenderData("", 1);
                        ulists = App.getDBcApplication().queryCalenderData("", 0);
                    }
                    break;
            }
            int[] dateArr = CalendarUtil.getYMD(new Date());
            synchronized (getActivity()) {
                calenderView.setData(getMonthOfDayList(dateArr[0], dateArr[1]), true);
            }
            sharedPrefUtil.putString(getActivity(), ShareFile.USERFILE, ShareFile.IS_MONTH_RE, "0");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    Handler calenderhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg == null) {
                return;
            }
            switch (msg.what) {
                case 0:
                    if (standard_month == 1) {
                        standard_month = 12;
                        standard_year--;
                    } else {
                        standard_month--;
                    }
                    calenderView.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.right_in));
                    calenderView.setData(getMonthOfDayList(standard_year, standard_month), true);

                    break;

                case 1:
                    if (standard_month == 12) {
                        standard_month = 1;
                        standard_year++;
                    } else {
                        standard_month++;
                    }
                    calenderView.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.left_in));
                    calenderView.setData(getMonthOfDayList(standard_year, standard_month), true);

                    break;
            }
        }
    };


    @Override
    public void onItemClick(View view, int postion, CalendarBean bean) {
        if (sharedPrefUtil.getString(getActivity(), ShareFile.USERFILE, ShareFile.TYPEUID, "").isEmpty()) {
            if (bean.mothFlag == 0) {
                String month = bean.moth + "";
                String day = bean.day + "";
                if (bean.moth < 10) {
                    month = "0" + bean.moth;
                }

                if (bean.day < 10) {
                    day = "0" + bean.day;
                }

                final String selected_day = bean.year + "-" + month + "-" + day;
                MonthFragmentAddDialog dialog = new MonthFragmentAddDialog(getActivity(),
                        R.style.dialog_translucent, getActivity().getWindowManager(), selected_day, newopeartTypes);
                dialog.show();
                dialog.setCallBack(new MonthFragmentAddDialog.CallBack() {
                    @Override
                    public void reminderEditTime() {
                        try {
                            loaddata();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        month_tv_right.setText("" + (standard_month > 9 ? standard_month : "0" + standard_month));
                        year_tv_right.setText("月/" + standard_year);
                        calenderView.setData(getMonthOfDayList(standard_year, standard_month), true);
                    }
                });
            }
        }
    }

    @Override
    public void onLongItemClick(View view, int postion, CalendarBean bean) {
        if (bean.mothFlag == 0) {
            String month = bean.moth + "";
            String day = bean.day + "";
            if (bean.moth < 10) {
                month = "0" + bean.moth;
            }

            if (bean.day < 10) {
                day = "0" + bean.day;
            }

            final String selected_day = bean.year + "-" + month + "-" + day;
            ArrayList<Map<String, String>> intentmaplist = new ArrayList<>();
            for (Map<String, String> map : ulists) {
                if (map.get(ScheduleTable.schDate).equals(selected_day)) {
                    intentmaplist.add(map);
                }
            }
            for (Map<String, String> map : dblists) {
                if (map.get(ScheduleTable.schDate).equals(selected_day)) {
                    intentmaplist.add(map);
                }
            }
//            if (intentmaplist.size() > 0) {
            Intent intent = new Intent(getActivity(), MonthViewActivity.class);
            intent.putExtra("date", selected_day);
            intent.putExtra("newopeartType", newopeartTypes);
            startActivity(intent);
//            }
        }
    }

    int newopeartTypes = 0;


}
